Search code examples
javapathfilepathfilewriter

How to write data to txt file in java?


My class:

public class Test{
public static void writeSmth() {
        try {
            BufferedWriter out = new BufferedWriter(
                    new FileWriter("one.txt"));
            out.write("content");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Location of txt file:

/ProjectName/one.txt

when i try to write data nothing happens with this file. I tried:

BufferedWriter out = new BufferedWriter(
                        new FileWriter("/ProjectName/one.txt"));

Got java.io.FileNotFoundException tried:

BufferedWriter out = new BufferedWriter(
                        new FileWriter("./one.txt"));

Still nothing happens.

What is the problem?


Solution

  • You can use System.getProperty(String) to get the user's home directory. For text output I'd prefer a PrintStream. Next, you can write to your output file relative to that path. I'd also use a try-with-resources Statement. Somethin like,

    File file = new File(System.getProperty("user.home"), "one.txt");
    try (PrintStream ps = new PrintStream(file)) {
        ps.println("content");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }