---
title: "How to Write text file Java"  
description: "How to Write text file Java"  
author: "Anonymous User"  
published: 2013-10-04  
updated: 2013-10-04  
canonical: https://www.mindstick.com/forum/1578/how-to-write-text-file-java  
category: "java"  
tags: ["java"]  
reading_time: 2 minutes  

---

# How to Write text file Java

The following [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii) does not [produce](https://yourviews.mindstick.com/view/83488/how-much-power-do-solar-panels-produce) a [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) (I can't see the file anywhere). What is [missing](https://answers.mindstick.com/qa/52138/international-missing-children-s-day-2019-was-observed-on)?

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

\

## Replies

### Reply by Anonymous User

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...


---

Original Source: https://www.mindstick.com/forum/1578/how-to-write-text-file-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
