I am making a simple program that put data into a file using FileWriter
.
But I am facing a problem. My code is creating the fie but not putting data into the file.
import java.io.*;
class Temp
{
public static void main(String args[])throws Exception
{
FileWriter fw=new FileWriter("ma.txt");
BufferedWriter bw=new BufferedWriter(fw);
String str="dslkm dsk";
bw.write(str);
}
}
Why is this happening?
You need to flush and close the writer.
bw.flush();
bw.close();
Even just closing the writer should be enough, since it automatically flushes before closing.
Your code should be:
public static void main(String args[])throws Exception
{
FileWriter fw=new FileWriter("ma.txt");
BufferedWriter bw=new BufferedWriter(fw);
String str="dslkm dsk";
bw.write(str);
bw.flush();
bw.close();
}
A file writer always need to be closed or flushed. Otherwise there is no guarantee to the write the bytes
/ characters
in it to be written in your file.And it's better to use fileWriter
with try-catch-finally
block -
try {
FileWriter fw=new FileWriter("ma.txt");
BufferedWriter bw=new BufferedWriter(fw);
String str="dslkm dsk";
bw.write(str);
} catch (IOException ex){
System.err.println("Couldn't log this: "+s);
}finally{
bw.close();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.