Home > DeveloperSection > Forums > How to Write text file Java
Chintoo Semi

Total Post:135

Points:947
Posted on    October-04-2013 9:14 AM

 Java Java 
Ratings:


 1 Reply(s)
 783  View(s)
Rate this:

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


jacob rasel
jacob rasel

Total Post:88

Points:616
Posted on    October-04-2013 9:30 AM

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

Basically, where you think the file is been written and where the file is actually been written are not equal (hmmm, perhaps I should write and 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 override any existing files. If you want to append the text to the file you should...

writer = new BufferedWriter(new FileWriter(logFile, true));

Instead...


Modified On Mar-15-2016 05:48:56 AM

Don't want to miss updates? Please click the below button!

Follow MindStick