1

I was testing out writing to files with this code:

package files;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class FileTest1 
{
public static void main(String[] args)
{
    try
    {
        try
        {
            File f = new File("filetest1.txt");
            FileWriter fWrite = new FileWriter(f);
            BufferedWriter fileWrite = new BufferedWriter(fWrite);
            fileWrite.write("This is a test!");
        }
        catch(FileNotFoundException e)
        {
            System.out.print("A FileNotFoundException occurred!");
            e.printStackTrace();
        }
    }
    catch(IOException e)
    {
        System.out.println("An IOException occurred!:");
        e.printStackTrace();
    }
}

}

Nothing happens when it is executed. "This is a test!" is not written, nor the StackTrace or the "A/An [exception] occurred!"... I don't know what's causing the problem. I have fileTest1.txt in the package right under the file...

  • Your code says `filetest1.txt` and your comment says `fileTest1.txt`? Most file systems are case sensitive. You will probably also want to flush your file and then close it. – Hyperboreus Aug 16 '13 at 23:32
  • Can you show the command you use to run your program? Are you doing it throw some IDE? What platform are you running on? Also, you say "I have fileTest1.txt in the package right under the file" -- can you clarify what that means? – Jason C Aug 16 '13 at 23:48
  • Also, are you sure you are actually running the program you think you are running? Are you truly running `FileTest1`? Add a `System.println("Hello");` or something as the first line of main. Does it display? Is the working directory different than you expect? Is `filetest1.txt` being created somewhere else? – Jason C Aug 16 '13 at 23:48

4 Answers4

4

A BufferedWriter does just that, it buffers the output before it is written to the destination. This can make the BufferedWriter faster to use as it doesn't have to write to a slow destination, like a disk or socket, straight away.

The contents will be written when the internal buffer is to full, you flush the Writer or close the writer

Remember, if you open it, you should close it...

For example...

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TestFileWriter {

    public static void main(String[] args) {
        try {
            BufferedWriter fileWrite = null;
            try {
                File f = new File("filetest1.txt");
                System.out.println("Writing to " + f.getCanonicalPath());
                FileWriter fWrite = new FileWriter(f);
                fileWrite = new BufferedWriter(fWrite);
                fileWrite.write("This is a test!");
                fileWrite.flush();
            } catch (FileNotFoundException e) {
                System.out.print("A FileNotFoundException occurred!");
                e.printStackTrace();
            } finally {
                try {
                    // Note, BufferedWriter#close will also close
                    // the parent Writer...
                    fileWrite.close();
                } catch (Exception exp) {
                }
            }
        } catch (IOException e) {
            System.out.println("An IOException occurred!:");
            e.printStackTrace();
        }
        try {
            BufferedReader br = null;
            try {
                File f = new File("filetest1.txt");
                System.out.println("Reading from " + f.getCanonicalPath());
                FileReader fReader = new FileReader(f);
                br = new BufferedReader(fReader);
                String text = null;
                while ((text = br.readLine()) != null) {
                    System.out.println(text);
                }
            } catch (FileNotFoundException e) {
                System.out.print("A FileNotFoundException occurred!");
                e.printStackTrace();
            } finally {
                try {
                    // Note, BufferedWriter#close will also close
                    // the parent Writer...
                    br.close();
                } catch (Exception exp) {
                }
            }
        } catch (IOException e) {
            System.out.println("An IOException occurred!:");
            e.printStackTrace();
        }
    }
}

If you are using Java 7, you may like to take a look at try-with-resources

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Okay... I fixed the capitolization and added: fileWriter.flush() and fileWriter.close(), but still nothing happens. – user2604533 Aug 16 '13 at 23:36
  • I wrote that in, but still, nothing happened. – user2604533 Aug 16 '13 at 23:42
  • Can I ask you to try my sample code. Because it works fine for me. Also, make sure you have write access to the location you are trying to write to... – MadProgrammer Aug 16 '13 at 23:42
  • The I would suggest that you are trying to write to a location you don't have write access. Make sure you delete only old `filetest1.txt` files and make sure you are writing to a location you know you can write to – MadProgrammer Aug 16 '13 at 23:47
  • 1
    I think OP is checking a different file with the same name, and not the file that's being written to. – jlordo Aug 16 '13 at 23:48
  • @MadProgrammer A permissions issues would generate an exception. – Jason C Aug 16 '13 at 23:50
  • @user2604533: Can you show the command you use to run your program? Are you doing it through some IDE? What platform are you running on? Also, you say "I have fileTest1.txt in the package right under the file" -- can you clarify what that means? Are you sure you are actually running the program you think you are running? Are you truly running `FileTest1`? Add a `System.println("Hello");` or something as the first line of main. Does it display? Is the working directory different than you expect? Is `filetest1.txt` being created somewhere else? – Jason C Aug 16 '13 at 23:51
  • @JasonC Not on Windows 7 :P - Had this problem, took us two weeks to figure it out :P – MadProgrammer Aug 16 '13 at 23:52
  • @MadProgrammer I don't ever recall running into a problem like that on Windows 7, but I 100% believe it. – Jason C Aug 16 '13 at 23:53
  • 2
    @user2604533 I've updated my example to print the absolute path of the file being written to so you know, without a doubt, where the file is begin written. I've also added a read test to read the file back in – MadProgrammer Aug 16 '13 at 23:53
  • If an exception is not being thrown due to an access denied error, perhaps the file exists but is being held open by some other process; maybe a previous run of his program or a text editor. He does say he already has a "filetest1.txt" somewhere. – Jason C Aug 16 '13 at 23:54
  • 1
    @JasonC Our application was trying to write files into the `Program Files` directory as a normal user and the files just wouldn't write, even though `File#canWrite` was returning `true` - it turns out to be a bug in Java with the UAC - I'd like those two weeks of my life back :P – MadProgrammer Aug 16 '13 at 23:54
  • 1
    Strange. Deleted the filetest1.txt file from the package explorer in eclipse, then looked it up in the search bar to find it still existing, with This is a test! written in it, but i cannot edit it further... – user2604533 Aug 16 '13 at 23:55
  • @MadProgrammer Fascinating; and I'm filing that Java/UAC (non)interaction a way. You may have saved me two weeks at some unknown point in the future. I generally disable UAC immediately out of the box on every machine I configure. – Jason C Aug 16 '13 at 23:55
  • @user2604533: You didn't say you were viewing it in the Eclipse browser! Eclipse just stinks sometimes about updating resources that are modified outside the editor... I'd just clean your project then restart Eclipse and see if things make more sense after that. – Jason C Aug 16 '13 at 23:56
  • @JasonC Yeah, our dev machines had the UAC disable, so worked fine for us to, but when we tried to deploy to a client machine it broke...:P – MadProgrammer Aug 16 '13 at 23:56
  • @MadProgrammer You have my deepest condolences. – Jason C Aug 16 '13 at 23:57
  • @JasonC I got it :) I saw in the start menu that whenever i ran the program, it would create a new version of the file in a different place in the eclipse project, so I put it there and it worked. – user2604533 Aug 17 '13 at 00:16
1

After

fileWrite.write("This is a test!");

you have to flush() the writer. To avoid leaking of resources you should also close() the writer (which automatically flushes it).

So you need to add:

fileWrite.close();
jlordo
  • 37,490
  • 6
  • 58
  • 83
1

Use BufferedWriter.flush() and BufferedWriter.close(). Additional info here http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html

blgt
  • 8,135
  • 1
  • 25
  • 28
0

You must call close() or at least flush() on the writer in order for the buffer to be really written to the file.

FrankPl
  • 13,205
  • 2
  • 14
  • 40
  • 1
    You should **always** close any resource you open, this can cause problems later - IMHO – MadProgrammer Aug 16 '13 at 23:35
  • I agree, and I would even do that in a `finally` to be really sure. But the question was why the data is not visible, and that can be reached via `flush()` alone. – FrankPl Aug 16 '13 at 23:38
  • (nit pick) The whole problem could actually be solved by just calling `close`, which not only helps solve the OP's problem, but demonstrates good practices. If the OP was writing to a `Socket`, it would defiantly agree with adding `flush` - IMHO – MadProgrammer Aug 16 '13 at 23:45