How do I save a String to a text file using Java?

后端 未结 24 1090
不知归路
不知归路 2020-11-22 04:18

In Java, I have text from a text field in a String variable called \"text\".

How can I save the contents of the \"text\" variable to a file?

24条回答
  •  心在旅途
    2020-11-22 04:52

    I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:

    // This is where the file goes.
    File destination = new File("file.txt");
    // This line isn't needed, but is really useful 
    // if you're a beginner and don't know where your file is going to end up.
    System.out.println(destination.getAbsolutePath());
    try {
        Files.write(text, destination, Charset.forName("UTF-8"));
    } catch (IOException e) {
        // Useful error handling here
    }
    

提交回复
热议问题