Languages

Java - how to save String to file?

10 points
Asked by:
illona
316

What is the best way how to save simple String to file in java?

There is more then one way to do it, which one is the best?

1 answer
5 points
Answered by:
illona
316

Quick solution:

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SaveFileExample {

    public static void main(String[] args) throws IOException {

        String text = "Hello world";
        Path path = Paths.get("C:\\test\\my-file.txt");

        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            writer.write(text);
            writer.flush(); // ensure long text will be saved
        }
    }
}

By default Files.newBufferedWriter uses StandardCharsets.UTF_8 (java.nio.charset.StandardCharsets.UTF_8) encoding.

More examples:

 

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join