63

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();
}
Ashish Aggarwal
  • 2,950
  • 2
  • 21
  • 43
William Falcon
  • 9,426
  • 11
  • 59
  • 106
  • 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 – MadProgrammer Apr 02 '13 at 01: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 02 '13 at 01: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... – MadProgrammer Apr 02 '13 at 01: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. – MadProgrammer Apr 02 '13 at 01:21
  • different language... Not familiar with it, and looking for the file.save method – William Falcon Apr 02 '13 at 01:35

8 Answers8

121

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));
MadProgrammer
  • 323,026
  • 21
  • 204
  • 329
  • 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 '13 at 22:59
  • @third_eye You're spoiling my fun ;) Nice catch, I've updated the answer – MadProgrammer Sep 18 '13 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 '17 at 08: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.

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

In java 7 can now do

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

and w.close will be done automatically

guest
  • 141
  • 1
  • 3
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();
jts3304
  • 63
  • 1
  • 3
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();
        }
    }
}
xtra
  • 1,075
  • 1
  • 12
  • 24
0

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

Snow
  • 29
  • 3
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!

Carlos López Marí
  • 1,084
  • 1
  • 12
  • 30