64

The following code does not produce a file (I can't see the file anywhere). What is missing?

try {
    //create a temporary file
    String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
        Calendar.getInstance().getTime());
    File logFile=new File(timeLog);

    BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
    writer.write (string);

    //Close writer
    writer.close();
} catch(Exception e) {
    e.printStackTrace();
}
5
  • 1
    1- Try calling writer.flush() before you close it. 2- You should be using a finally block to ensure that the Writer is closed even if there is an exception Apr 2, 2013 at 1:17
  • where are you trying to write the file to ? you need to specify the full path for timeLog. example is it under C:\ ?
    – grepit
    Apr 2, 2013 at 1:17
  • 1
    @user717630 Not really. Without the path, the file will be written the current "working" directory, which is typically the directory the program was executed in... Apr 2, 2013 at 1:19
  • 3
    Try adding System.out.println(logFile.getCanonicalPath()); just before you create the writer, this will tell you where the file is been written to. Apr 2, 2013 at 1:21
  • different language... Not familiar with it, and looking for the file.save method Apr 2, 2013 at 1:35

8 Answers 8

122

I think your expectations and reality don't match (but when do they ever ;))

Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))

public class TestWriteFile {

    public static void main(String[] args) {
        BufferedWriter writer = null;
        try {
            //create a temporary file
            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File logFile = new File(timeLog);

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());

            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write("Hello world!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }
        }
    }
}

Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:

writer = new BufferedWriter(new FileWriter(logFile, true));
3
  • 1
    Shouldn't the last part be: writer = new BufferedWriter(new FileWriter(logFile,true)); ?? Since the append parameter is for FileWriter not BufferedWriter.
    – third_eye
    Sep 18, 2013 at 22:59
  • @third_eye You're spoiling my fun ;) Nice catch, I've updated the answer Sep 18, 2013 at 23:37
  • It is safer and recommended to also specify the encoding: new FileWriterWithEncoding(logFile, "UTF-8", true) or so.
    – Florian F
    Mar 22, 2017 at 8:42
17

I would like to add a bit more to MadProgrammer's Answer.

In case of multiple line writing, when executing the command

writer.write(string);

one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,

System.out.println("\n");

Thus, the whole text comes as one big chunk of text which is undesirable in most cases. The newline character can be dependent on the platform, so it is better to get this character from the java system properties using

String newline = System.getProperty("line.separator");

and then using the newline variable instead of "\n". This will get the output in the way you want it.

1
  • 2
    writer.newLine() directly writes a line separator, taken from System.getProperty("line.separator")
    – Mike
    Dec 30, 2015 at 15:57
14

In java 7 can now do

try(BufferedWriter w = ....)
{
  w.write(...);
}
catch(IOException)
{
}

and w.close will be done automatically

0
5

It's not creating a file because you never actually created the file. You made an object for it. Creating an instance doesn't create the file.

File newFile = new File("directory", "fileName.txt");

You can do this to make a file:

newFile.createNewFile();

You can do this to make a folder:

newFile.mkdir();
1

Using java 8 LocalDateTime and java 7 try-with statement:

public class WriteFile {

    public static void main(String[] args) {

        String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
        File logFile = new File(timeLog);

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile))) 
        {
            System.out.println("File was written to: "  + logFile.getCanonicalPath());
            bw.write("Hello world!");
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}
1
  • You should always specify the encoding scheme.
    – SandRock
    Aug 19, 2020 at 8:38
0

You can try a Java Library. FileUtils, It has many functions that write to Files.

0

It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).

0

The easiest way for me is just like:

            try {
                FileWriter writer = new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
                writer.write("Wow, this is so easy!");
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

Useful tips & tricks:

  • Give it a certain path:

    new FileWriter("C:/Your/Absolute/Path/YourFile.txt");

  • New line

    writer.write("\r\n");

  • Append lines into existing txt

    new FileWriter("log.txt");

Hope it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.