I need to delete the contents of a file, before I write more information into it. I've tried different ways, such as where I delete the content but the file stays the same size, and when I start writing in it after the deletion, a blank hole appears to be the size of the deletion before my new data is written.
This is what I've tried...
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(path));
bw.write("");
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
And I've also tried this...
File f = new File(file);
FileWriter fw;
try {
fw = new FileWriter(f,false);
fw.write("");
}
catch (IOException e) {
e.printStackTrace();
}
Can someone please help me with a solution to this problem.
FileWriter (path, false)
The false will tell the writer to truncate the file instead of appending to it.
Try calling flush() before calling close().
FileWriter writer = null;
try {
writer = ... // initialize a writer
writer.write("");
writer.flush(); // flush the stream
} catch (IOException e) {
// do something with exception
} finally {
if (writer != null) {
writer.close();
}
}
It might be because you are not closing the FileWriter, fw.close(); also you dont need to "delete" the old data, just start writing and it will overwrite the old data. So make sure you are closing everywhere.
This works for me:
File f=new File(file);
FileWriter fw;
try {
fw = new FileWriter(f);
fw.write("");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
Related
I have closed file steam in try/finally, but code analysis warns me:
Possible failure to close a FileOutputStream
Possible failure to close a PrintWriter
Possible failure to close an OutputStreamWriter
How can failure happen? How can I ensure the FileStream is closed?
public void writeFile(String filepath)
{
BufferedWriter bw = null;
PrintWriter pw = null;
try {
File file = new File(filepath);
bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
pw = new PrintWriter(bfw);
//do something
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
bfw.close();
pw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
If you are using Java-7 and above then you can use try with resources
File file = new File(filepath);
try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
PrintWriter pw = new PrintWriter(bfw);)
{
...
}
catch(Exception exception) //This is optional
{
exception.printStackTrace();
}
You can use catch and finally blocks with try-with-resources statement just like an ordinary try statement.
Hope this helps!
How can failure happen?
See your finally block:
finally{
try{
bfw.close(); <== exception occured here
pw.close(); <== this is not execute
}catch(Exception e){
e.printStackTrace();
}
}
What if an exception occurs in bfw.close()? pw.close() will never execute. And this leads to a resource leak.
How can I ensure the FileStream is closed?
Someone already pointed out using try/catch/finally inside finally.
But if you don't like to see so many try catch finally I would suggest you to use a library like Apache Commons IO.
Solution:
try {
........
} finally {
IOUtils.closeQuietly(bfw);
IOUtils.closeQuietly(pw);
}
And yes, you always have try-with-resources if using Java 7 or above.
If exception happens when closing bw you will not close pw. Try this:
finally{
try{
bw.close();
} catch(Exception e){
e.printStackTrace();
} finally {
pw.close();
}
}
I would like to make you think about a tiny problem using the method printStackTrace(PrintWriter s). I need to use it in append mode.
The following example is explaining what I mean:
try {
} catch (Exception e) {
try {
e.printStackTrace(new PrintWriter(new FileWriter("mylog.txt", true)));
} catch (IOException ioe) {
System.out.println("I can't open the file mylog.txt");
}
}
Note that
new FileWriter("mylog.txt", true);
is the way I open the file (and create it the first time because it doesn't exist) in append mode.
The result is that in the file there is only the last exception and not a series of exceptions. One time it occurred that the method opened the file in which it didn't write anything.
How can I solve this problem?
Thank you.
Adding to what krzyk mentioned
Per OutputStreamWriter.close() : Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
As mentioned, if you do not call close and this try{}catch is getting fired frequently, you are not flushing content to file.
It should written like
try {
} catch (Exception e) {
try {
FileWriter fw = new FileWriter("mylog.txt", true)
e.printStackTrace(new PrintWriter(fw));
fw.close();
} catch (IOException ioe) {
System.out.println("I can't open the file mylog.txt");
}
}
A better approach will be
FileWriter fw = new FileWriter("mylog.txt", true);
PrintWriter pw = new PrintWriter(fw);
try {
} catch (Exception e) {
try {
e.printStackTrace(pw);
} catch (IOException ioe) {
System.out.println("I can't open the file mylog.txt");
}
}finally {
pw.close();
fw.close();
}
You should close the created Writers, not closing it might cause the problems you describe.
try (PrintWriter writer = new PrintWriter(new FileWriter("mylog.txt", true))) {
e.printStackTrace(writer);
}
How do I use FileWriter to actually write into a file and then open it on notepad and see what I wrote? This is what I tried so far:
package Experimental;
import java.io.*;
public class IO {
public static void main (String args[]) {
File f = new File("testFile.txt");
//Outputting into a file
try {
PrintWriter filePrint = new PrintWriter(
new BufferedWriter(new FileWriter(f,true))
);
filePrint.println("testing, testing, printing into a file (apparently)");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Don't forget to close your FileWriter once you are done writing to it.
You should flush and close the PrintWriter like this:
File file = new File("testFile.txt");
PrintWriter filePrint = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
try
{
try
{
filePrint.println("testing, testing, printing into a file (apparently)");
filePrint.flush();
}
finally
{
filePrint.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
I have a java application that needs to write a lot of data into individual lines in a text file. I wrote the code below to do this, but for some reason, it is not writing anything to the text file. It does create the text file, but the text file remains empty after the program is done running. Can anyone show me how to fix the code below so that it actually fills the output file with as many lines of output as it is called upon to do?
public class MyMainClass{
PrintWriter output;
MyMainClass(){
try {output = new PrintWriter("somefile.txt");}
catch (FileNotFoundException e1) {e1.printStackTrace();}
anotherMethod();
}
void anotherMethod(){
output.println("print some variables");
MyOtherClass other = new MyOtherClass();
other.someMethod(this);
}
}
public class MyOtherClass(){
void someMethod(MyMainClass mmc){
mmc.output.println("print some other variables")
}
}
How you are going about doing this seems very strange to me. Why don't you write one method that takes in a string and then writes it to your file? Something like this should work fine
public static void writeToLog(String inString)
{
File f = new File("yourFile.txt");
boolean existsFlag = f.exists();
if(!existsFlag)
{
try {
f.createNewFile();
} catch (IOException e) {
System.out.println("could not create new log file");
e.printStackTrace();
}
}
FileWriter fstream;
try {
fstream = new FileWriter(f, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(inString+"\n");
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("could not write to the file");
e.printStackTrace();
}
return;
}
Use the other constructor:
output = new PrintWriter(new FileWriter("somefile.txt"), true);
According to JavaDoc:
public PrintWriter(Writer out, boolean autoFlush)
Creates a new PrintWriter.
Parameters:
out - A character-output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer
Use other constructor new PrintWriter(new PrintWriter("fileName"), true) for auto-flushing data or
Use flush() and close() when you're done writing
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am using this code to write to a file in java. it has always worked and I am 100% sure its right. But still the file does not get written.
I don't even get an error.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class writetofile {
public static void main(String [] args){
FileWriter fw;
try {
fw = new FileWriter("testfile.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("this is test");
bw.write("this is test");
bw.write("this is test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Could it be some other problem?
You are not calling the close() method on the BufferedWriter object. That means the buffers never get flushed. Add bw.close() after your last bw.write() statements.
try fw.flush() and fw.close()
You need to flush the buffer and you should close the file as well:
try {
fw = new FileWriter("/tmp/testfile.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("this is test");
bw.write("this is test");
bw.write("this is test");
bw.flush();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Also you should handle the IOException from the actual file writing separately from the file closing so you won't leave the file descriptor opened at the end:
FileWriter fw = null;
try {
fw = new FileWriter("/tmp/testfile.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("this is test");
bw.write("this is test");
bw.write("this is test");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Make sure you call bw.close() before your method exits. If the buffer doesn't get flushed your file wont get written.
Try closing the stream with sw.close() or the data may still be cached and not actually written to disk.