Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

What's the easiest way to create and write to a (text) file in Java?

1 Answer

0 votes
by (46k points)

To create and write a text file :

List<String> lines = Arrays.asList("The first line", "The second line");

Path file = Paths.get("the-file-name.txt");

Files.write(file, lines, StandardCharsets.UTF_8);

//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Or you can also use this:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8)))

 {

    writer.write("text to write");

catch (IOException ex) 

{

    // Handle me

To know more click here.

Related questions

0 votes
1 answer
asked Sep 16, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...