I use a FileWriter and a BufferWriter to write in a file. The file \"test.txt\" is created but nothing is written inside.
The file should be written in the ActionEve
you have to flush your writer.
out.flush();
out.close();
put these two lines after all writing is done to close the file
Follow these Sequence to successfully write to a file....
File f = new File("d:\\test.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Hello........"); // Writing to the file
bw.close(); // Close the BufferedWriter
fw.close(); // Close the FileWriter
Closing of Streams are important....
Close or flush the writer:
FileWriter fw = new FileWriter("test.txt");
BufferedWriter out = new BufferedWriter(fw);
out.write("aString");
out.close();
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestAndDelete {
public static void main(String[] args) throws IOException {
String test="hi how are you";
File file =new File("D:/abcd/ravi.json");
FileWriter fw=new FileWriter(file.getAbsoluteFile());
BufferedWriter bw=new BufferedWriter(fw);
bw.append(test);
bw.close();
}
}
Here,
try
{
FileWriter fw = new FileWriter("test.txt");
BufferedWriter out = new BufferedWriter(fw);
out.write("aString");
}
catch (IOException e)
{
e.printStackTrace();
}
You wrapped it in a BufferedWriter
which has a default buffer size of 8KB. So as long as you don't write more than 8KB and don't flush/close it, then it won't appear in the target file.
You need to close the writer when you're done with it. This will flush any buffers and release any locks on the file. The normal idiom is to close it in the finally
block of the very same try
block as where it was been created. This way you guarantee that it's also closed in case of exceptions, hereby preventing resource leaking and forever locked files.
Writer writer = null;
try {
writer = new BufferedWriter(new FileWriter("test.txt"));
writer.write("aString");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
Alternatively, if you're already on Java 7, then you can also use the new try-with-resources statement. It'll automatically close the resource when you leave the try
block, resulting in less boilerplate code.
try (Writer writer = new BufferedWriter(new FileWriter("test.txt"))) {
writer.write("aString");
} catch (IOException e) {
e.printStackTrace();
}
By the way, I'd work on exception handling as well. Rather display the enduser some sensible error message instead of plain printing it to the stdout and ignoring it further.