writing to a file problem [duplicate] - java

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.

Related

How to solve failure to close a FileStream

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();
}
}

BufferedWriter writing to console instead of text file

These are the contents of the constructor of a class which is called by the main method.
File f = null;
Scanner s;
try {
f = new File(getClass().getResource("/LOL.txt").toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
s = new Scanner(f);
while(s.hasNextLine()) System.out.println(s.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(f.getAbsoluteFile(), false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("LOL");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Output in the console:
LOL
The contents of the file remain unchanged even after repeated runs. My IDE is eclipse
You parametrize your FileWriter with boolean append set as false.
Therefore, the same file will be written over every time that given constructor is executed, and "LOL" will be printed in it.
Before printing "LOL", a Scanner reads each line and prints it, hence the LOL printed in our system out.
Also note, you probably want to declare your FileWriter and BufferedWriter out of the try block, so you can flush and close them in a finally block.
This post only contains the initial question, as-is with everything corrected to avoid several resource-related bugs. It assumes Java 6 or lower.
I shouldn't get any upvote so please don't ;)
package so39452286;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
File file = new File(getClass().getResource("/LOL.txt").toURI());
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
if (scanner != null) {
scanner.close();
}
}
Writer writer = null; // Holds the main resource, not the wrapping ones.
try {
writer = new FileWriter(file.getAbsolutePath(), false);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("LOL");
bw.flush(); // You forgot to flush. Ok, close() does it, but it's always better to be explicit about it.
} finally {
if (writer != null) {
writer.close();
}
}
} catch (Exception e) {
// Do something with e.
e.printStackTrace(System.err);
}
}
}

Exception - printStackTrace(Printwriter s) method

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);
}

FileWriter writing into file

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();
}

Deleting file contents android

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();
}

Categories