What is the simplest way to write a text file in Java?

前端 未结 9 1217
情歌与酒
情歌与酒 2021-01-01 09:55

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D

I searched the web and found this co

相关标签:
9条回答
  • 2021-01-01 10:32
    String content = "your content here";
    Path path = Paths.get("/data/output.txt");
    if(!Files.exists(path)){
        Files.createFile(path);
    }
    BufferedWriter writer = Files.newBufferedWriter(path);
    writer.write(content);
    
    0 讨论(0)
  • 2021-01-01 10:47

    In Java 11 or Later, writeString can be used from java.nio.file.Files,

    String content = "This is my content";
    String fileName = "myFile.txt";
    Files.writeString(Paths.get(fileName), content); 
    

    With Options:

    Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
    

    More documentation about the java.nio.file.Files and StandardOpenOption

    0 讨论(0)
  • 2021-01-01 10:48

    Files.write() the simple solution as @Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.

    So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)

    List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
    
    Path path = Paths.get(fullFileName);
    try (BufferedWriter writer = Files.newBufferedWriter(path)) {   
        writer.write(lines.stream()
                          .reduce((sum,currLine) ->  sum + "\n"  + currLine)
                          .get());
    }     
    

    In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.

    0 讨论(0)
提交回复
热议问题