[java] How to Write text file Java

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

This question is related to java file file-io

The answer is


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!


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.


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


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

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).


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

In java 7 can now do

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

and w.close will be done automatically


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js