Why doesn't PrintWriter work with Thread.sleep() - java

PrintWriter works (it writes to the external file) until I add the line that says Thread.sleep(100);. Then the code still compiles just fine, and it continues writing to the console, but it won't print to the external file. But I can't figure out why?
import java.io.*;
import java.io.PrintWriter;
import java.io.File;
import javax.swing.*;
public class RecordMouse {
public static void main(String[] args) throws InterruptedException{
String line = "";
// string for filename
String filename = System.currentTimeMillis() + "out.txt";
// create file
File file = new File(filename);
// create writer
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
while(true){
//Thread.sleep(100);
System.out.println(System.currentTimeMillis() + " hi \n");
printWriter.println(System.currentTimeMillis() + " hi");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
}
}

The difference sleep makes in your case is that it slows down frequency of writes and and it will take a while until the writes get flushed into the file. By removing the sleep you are causing the write flush to happen much more earlier. Change the sleep time into something smaller (like 5 instead of 100) or wait a little longer and see that the file gets written over.

Related

Java how to start reading file after Nth line with good performance

I have a file where data keeps appending. I am using java to read that file and process the data. To get the latest data, I am storing the offset till where I have read the file and continue reading from that offset when java process runs next.
RandomAccessFile f = new RandomAccessFile("file.txt","r");
f.seek(offset)
The problem here is performance. Its around 300 times slower than BufferedReader. Is it possible to resume reading from particular line using BufferedReader?
import java.io.RandomAccessFile;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
RandomAccessFile objReader = null;
try {
String strCurrentLine;
long startTime = System.currentTimeMillis();
objReader = new RandomAccessFile("auditlog-2018-12-21.txt", "r");
while ((strCurrentLine = objReader.readLine()) != null) {
}
System.out.println(System.currentTimeMillis()-startTime);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Reading 30M file having 100,000 lines takes 12 s while replacing RandomAccessFile with BufferReader takes less than 400ms.
you can try the below code
try {
BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"), StandardCharsets.UTF_8);
List<String> line = reader.lines().skip(31).limit(1).collect(Collectors.toList());
line.stream().forEach(System.out::println);
}catch(Exception e){
}

Save to text file [duplicate]

In Java, I have text from a text field in a String variable called "text".
How can I save the contents of the "text" variable to a file?
If you're simply outputting text, rather than any binary data, the following will work:
PrintWriter out = new PrintWriter("filename.txt");
Then, write your String to it, just like you would to any output stream:
out.println(text);
You'll need exception handling, as ever. Be sure to call out.close() when you've finished writing.
If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
You will still need to explicitly throw the java.io.FileNotFoundException as before.
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
static void writeStringToFile(File file, String data, Charset charset)
which allows you to write text to a file in one method call:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));
You might also want to consider specifying the encoding for the file as well.
In Java 7 you can do this:
String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());
There is more info here:
http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
Take a look at the Java File API
a quick example:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.
In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:
Files.writeString(Path.of("my", "path"), "My String");
And the second method (see JavaDoc here) allows to specify an individual charset:
Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);
Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:
Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
You can use the modify the code below to write your file from whatever class or function is handling the text. One wonders though why the world needs a new text editor...
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
String str = "SomeMoreTextIsHere";
File newTextFile = new File("C:/thetextfile.txt");
FileWriter fw = new FileWriter(newTextFile);
fw.write(str);
fw.close();
} catch (IOException iox) {
//do stuff with exception
iox.printStackTrace();
}
}
}
I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:
// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
// Useful error handling here
}
Using Java 7:
public static void writeToFile(String text, String targetFilePath) throws IOException
{
Path targetPath = Paths.get(targetFilePath);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}
In case if you need create text file based on one single string:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class StringWriteSample {
public static void main(String[] args) {
String text = "This is text to be saved in file";
try {
Files.write(Paths.get("my-file.txt"), text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use Apache Commons IO api. Its simple
Use API as
FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");
Maven Dependency
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Use this, it is very readable:
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
import java.io.*;
private void stringToFile( String text, String fileName )
{
try
{
File file = new File( fileName );
// if file doesnt exists, then create it
if ( ! file.exists( ) )
{
file.createNewFile( );
}
FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( text );
bw.close( );
//System.out.println("Done writing to " + fileName); //For testing
}
catch( IOException e )
{
System.out.println("Error: " + e);
e.printStackTrace( );
}
} //End method stringToFile
You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.
You could do this:
import java.io.*;
import java.util.*;
class WriteText
{
public static void main(String[] args)
{
try {
String text = "Your sample content to save in a text file.";
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(text);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
return ;
}
};
Using org.apache.commons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
If you only care about pushing one block of text to file, this will overwrite it each time.
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
FileOutputStream stream = null;
PrintStream out = null;
try {
File file = chooser.getSelectedFile();
stream = new FileOutputStream(file);
String text = "Your String goes here";
out = new PrintStream(stream);
out.print(text); //This will overwrite existing contents
} catch (Exception ex) {
//do something
} finally {
try {
if(stream!=null) stream.close();
if(out!=null) out.close();
} catch (Exception ex) {
//do something
}
}
}
This example allows the user to select a file using a file chooser.
Basically the same answer as here, but easy to copy/paste, and it just works ;-)
import java.io.FileWriter;
public void saveToFile(String data, String filename) {
try (
FileWriter fw = new FileWriter(filename)) {
fw.write(data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void generateFile(String stringToWrite, String outputFile) {
try {
FileWriter writer = new FileWriter(outputFile);
writer.append(stringToWrite);
writer.flush();
writer.close();
log.debug("New File is generated ==>"+outputFile);
} catch (Exception exp) {
log.error("Exception in generateFile ", exp);
}
}
It's better to close the writer/outputstream in a finally block, just in case something happen
finally{
if(writer != null){
try{
writer.flush();
writer.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):
String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));
See javadoc:
Write lines of text to a file. Each line is a char sequence and is
written to the file in sequence with each line terminated by the
platform's line separator, as defined by the system property
line.separator. Characters are encoded into bytes using the specified
charset.
The options parameter specifies how the the file is created or opened.
If no options are present then this method works as if the CREATE,
TRUNCATE_EXISTING, and WRITE options are present. In other words, it
opens the file for writing, creating the file if it doesn't exist, or
initially truncating an existing regular-file to a size of 0. The
method ensures that the file is closed when all lines have been
written (or an I/O error or other runtime exception is thrown). If an
I/O error occurs then it may do so after the file has created or
truncated, or after some bytes have been written to the file.
Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.
If you wish to keep the carriage return characters from the string into a file
here is an code example:
jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
orderButton = new JButton("Execute");
textArea = new JTextArea();
...
// String captured from JTextArea()
orderButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// When Execute button is pressed
String tempQuery = textArea.getText();
tempQuery = tempQuery.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
out.print(tempQuery);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tempQuery);
}
});
I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation
Github repository
and the answer to your question is so easy
String path = FileSaver
.get()
.save(string.getBytes(),"file.txt");
My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.
As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.
public boolean writeStringToFile(File file, String string, Charset charset) {
if (file == null) return false;
if (string == null) return false;
return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}
public boolean writeBytesToFile(File file, byte[] data) {
if (file == null) return false;
if (data == null) return false;
FileOutputStream fos;
BufferedOutputStream bos;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data, 0, data.length);
bos.flush();
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return false;
}
return true;
}

PrintWriter.print blocks when the string is too long

I'm writing a wrapper program in java that's just supposed to pass arguments to other processes by writing to their standard in streams, and reading the response from their standard out streams. However, when the String I try to pass in is too large, PrintWriter.print simply blocks. No error, just freezes. Is there a good workaround for this?
Relevant code
public class Wrapper {
PrintWriter writer;
public Wrapper(String command){
start(command);
}
public void call(String args){
writer.println(args); // Blocks here
writer.flush();
//Other code
}
public void start(String command) {
try {
ProcessBuilder pb = new ProcessBuilder(command.split(" "));
pb.redirectErrorStream(true);
process = pb.start();
// STDIN of the process.
writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
System.out.println("Process ended catastrophically.");
}
}
}
If I try using
writer.print(args);
writer.print("\n");
it can handle a larger string before freezing, but still ultimately locks up.
Is there maybe a buffered stream way to fix this? Does print block on the processes stream having enough space or something?
Update
In response to some answers and comments, I've included more information.
Operating System is Windows 7
BufferedWriter slows the run time, but didn't stop it from blocking eventually.
Strings could get very long, as large as 100,000 characters
The Process input is consumed, but by line i.e Scanner.nextLine();
Test code
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import ProcessRunner.Wrapper;
public class test {
public static void main(String[] args){
System.out.println("Building...");
Wrapper w = new Wrapper("java echo");
System.out.println("Calling...");
String market = "aaaaaa";
for(int i = 0; i < 1000; i++){
try {
System.out.println(w.call(market, 1000));
} catch (InterruptedException | ExecutionException
| TimeoutException e) {
System.out.println("Timed out");
}
market = market + market;
System.out.println("Size = " + market.length());
}
System.out.println("Stopping...");
try {
w.stop();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Stop failed :(");
}
}
}
Test Process:
You have to first compile this file, and make sure the .class is in the same folder as the test .class file
import java.util.Scanner;
public class echo {
public static void main(String[] args){
while(true){
Scanner stdIn = new Scanner(System.in);
System.out.println(stdIn.nextLine());
}
}
}
I suspect that what is happening here is that the external process is writing to its standard output. Since your Java code doesn't read it, it eventually fills the external process's standard out (or err) pipe. That blocks the external process, which means that it can read from its input pipe .... and your Java process freezes.
If this is the problem, then using a buffered writer won't fix it. You either need to read the external processes output or redirect it to a file (e.g. "/dev/null" on Linux)
Writing to any pipe or socket by any means in java.io blocks if the peer is slower reading than you are writing.
Nothing you can do about it.

java how open file to write

I want to write a file but mixture of 3 bellow feature. how?
BufferedWriter , high volume data write needed
can append to exist text file
can set charset like "cp1256"
How mix all these features to open write file?
What you would do first is, Initiate your BufferedWriter :
`
String fileName = METHOD ARGUMENT, OR REGULAR STRING ("Output.txt");
BufferedWriter writer = null;
try {
File outFile = new File(fileName);
writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true));
writer.write(WHAT YOU WANT TO WRITE TO THE FILE);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
Now to explain the code so I'm not just spoon feeding it to you.
When we declare the BufferedWriter writer = null; , we are setting it to null so that we don't write anything without setting a Try/Catch Exception Handler around it.
Once we are within our exception handled, we initiate a File called outFile. This will be the file we are outputting. The Argument we give it is the name of the file name. (A String Value such as, "Output.txt") NOTE: You MUST add the extension or else it won't work the way you are hoping it does.
Next, when we reference our BufferedWriter again, we initiate a new one in the try/catch handler, and inside we initiate a FileWriter (What will be doing the writing to the file). We give it two arguments. The name of the Output File("Output.txt"), and we also supply a true argument. What this does is makes the File Appendable! When we write true, we are saying we want the file to be appendable.
Finally, we write to the file, whatever it is you want to write.
As for the third feature, I don't think that FileWriter's will allow you to choose the Character Encoding that you want to write with, so unless you aren't using UTF-8, then you may want to use a PrintWriter
To do this, you would simply replace our `writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true));
writer = new BufferedWriter(new PrintWriter(outputName, "UTF-8"));
I THINK this should work, if not, please let me know, I'll find a working solution.
public class WriteFile {
BufferedWriter out;
public void openFile(String file){
try {
out = new BufferedWriter(new FileWriter("data.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeInts(int[] ints){
try {
for(int i : ints) out.write(i+" ");
out.newLine();
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeFile(){
try {
if (out!=null)out.close();
} catch (IOException e) {
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
WriteFile wf = new WriteFile();
wf.openFile("test.txt");
wf.writeInts(new int[]{1,2,3,4,5});
wf.writeInts(new int[]{5,4,3,2,1});
wf.closeFile();
BufferedReader bf = new BufferedReader(new FileReader("test.txt"));
System.out.println(bf.readLine());
System.out.println(bf.readLine());
}
}
Output:
Line1: 1 2 3 4 5
Line2: 5 4 3 2 1

file handling and threads

I am trying to read three files using thread and then pass on the content to the writer class to write it to another file. The thread associated with the first file(which has line break in it) is returning back after every line break. Can anyone please tell me why is this happening. I will be pasting my code of the reader class.
package filehandling;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReading extends Thread{
BufferedReader fis;
int count=0;
FileWriting fw;
String str1, str2;
String ssr;
public FileReading(String str) throws IOException
{
//getting filename
File f= new File(str);
String strin;
strin= f.getName();
System.out.println(".." + strin);
//splitting filename to get the initial name
String stra[]= new String[2];
stra= strin.split("\\.");
str1= stra[0];
str2= stra[1];
System.out.println("extension name :" + str2);
System.out.println("filename :" + str1);
//associating file to input stream
fis= new BufferedReader(new FileReader(f));
}
public void run()
{
try
{
while((ssr=fis.readLine())!=null)
{
//file contents
System.out.println(ssr);
//writer thread
fw= new FileWriting(str1,ssr);
fw.start();
//assigning thread time to read,else next thread comes in
join(1000);
}
}
catch(Exception e)
{
System.out.println("exception : " + e.getMessage() + e.getStackTrace());
}
}
}
There is no sense in starting multiple threads within the process of reading a single file. Reading from a file data stream has no opportunity for parallel execution. But you can read three independent files in parallel by using three threads using an ordinary loop within each thread.
There is another misconception; you seem to think that you have to assign time to the threads. That’s wrong, you don’t need to think about that and you can’t do it the way you tried. When you start three threads, each of them reading and writing a file, all of them will go to sleep when no data are available and proceed on new data. The operating system will assign them CPU time appropriately.
Since you don’t have given a write part I can’t give you a code example for your task, but here is a simple example of reading three files in parallel and getting their contents back as a String:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ReadFile implements Callable<String>
{
public static void main(String[] args) throws InterruptedException
{
// enter the three file names here
String[] file={
"",
"",
""};
ExecutorService executorService = Executors.newFixedThreadPool(file.length);
List<Callable<String>> jobs=new ArrayList<>(file.length);
for(String f:file) jobs.add(new ReadFile(f));
List<Future<String>> all = executorService.invokeAll(jobs);
System.out.println("all files have been read in");
int i=0; for(Future<String> f:all) { i++;
System.out.println("file "+i+": ");
try
{
String contents = f.get();
System.out.println(contents);
} catch(ExecutionException ex)
{
ex.getCause().printStackTrace();
}
}
}
final String fileName;
public ReadFile(String file) {
fileName=file;
}
public String call() throws Exception {
String newLine=System.getProperty("line.separator");
StringBuilder sb=new StringBuilder();
try(BufferedReader r=new BufferedReader(new FileReader(fileName))) {
for(;;) {
String line=r.readLine();
if(line==null) break;
sb.append(line).append(newLine);
}
}
return sb.toString();
}
}
The line executorService.invokeAll will invoke the call methods of all provided ReadFile instances, each of them in another Thread. These threads read their files in a loop, becoming blocked whenever the I/O system has no new data for them, giving the other threads a chance to proceed. However, don’t expect three threads to run significantly faster the one thread processing the files one after another. The limiting factor is the I/O speed of your harddrive/SSD/etc. You have the most chances of getting more speed by multiple threads when all files lie on different devices.
Things will look different if the threads are not just reading or writing but also performing some computations.

Categories

Resources