Reputation: 11
I want to write some string to file (use Java 8). This code snippet compiles without any errors, but doesnt write to file....i'm noob ofcorz...any suggestion?
import java.io.BufferedWriter;
import java.io.FileWriter;
public class Main {
private static final String FILENAME = "C:\\IntelliJfiles\\write-to-
file\\src\\pl\\sca\\file.txt";
public static void main(String[] args) {
try {
String str = "kal";
BufferedWriter writer = new BufferedWriter(new
FileWriter(FILENAME));
writer.write(str);
System.out.println("Done");
}
catch (Exception e) {
System.out.println("There's no file");
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 5158
Reputation: 11
try this one
try {
String str = "kal";
BufferedWriter writer = new BufferedWriter(new
FileWriter(FILENAME));
writer.write(str);
writer.close();
System.out.println("Done");
}
Upvotes: 0
Reputation: 2444
An alternative to BufferWriter
is Files.write(Path, byte[], OpenOption...) if you aim at writing to a file only once.
String str = "test";
Path path = Paths.get("file.txt");
try {
byte[] bytes = str.getBytes(StandardsCharsets.UTF_8);
Files.write(path, bytes);
} catch (FileNotFoundException e) {
// Handle file absence.
} catch (IOException e) {
// Handle other exceptions related to io.
}
Note: As mentioned here catching Exception
doesn't indicate file absence in all cases. Catch FileNotFoundException
if you want to handle file absence or IOException
for all exceptional conditions related to io.
Upvotes: 0
Reputation: 874
You need to close the writer, you can use try-with-resources:
String str = "kal";
// we can use try-with-resources from java 7
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILENAME))) {
writer.write(str);
}
System.out.println("Done");
Or simply add writer.close()
:
writer.write(str);
writer.close();
Upvotes: -1
Reputation: 1361
It may not write to the file until you close it - writing to the disk is time consuming so it waits until enough characters are written before doing actually putting them in the file. That's what the Buffered in BufferedWriter
means. If you close it, it will "flush" the buffer onto the disk.
You can close it yourself using writer.close()
Or you can make use of try-with-resources, which will automatically close the writer:
try (FileWriter fw = new FileWriter("C:\\IntelliJfiles\\write-to-file\\src\\pl\\sca\\file.txt");
BufferedWriter bw = new BufferedWriter(fw)){
bw.write("kal");
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 2