在Java中编写文本文件的最简单方法是什么?

53

我想知道在Java中编写文本文件的最简单方法。请尽可能简单易懂,因为我是初学者:D

我在网上搜索到了这段代码,但我只理解了其中的50%。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}


我认为没有比这更简单的代码了。您能指出你不理解的部分吗? - Henrik
谢谢您的回复!我不太理解FileWriter和BufferedWriter类是做什么的。还有最后的catch(IOException)部分。请您能否简要地解释一下它们的作用。 - Georgi Koemdzhiev
9个回答

113

使用Java 7及以上版本,可以使用Files实现一行代码的解决方案:

String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());

12
最好指定一个字符集。 - BradHards
3
我同意,但问题是要求最简单的方法,这就是我认为最简单的方式。 - dazito
1
这会追加到还是覆盖指定的文件? - user7851115
2
后者 @Peri461 - James Gawron
4
为了向文件追加内容,我认为你可以使用Files.write(myPath, myString.getBytes(), StandardOpenOption.APPEND)。还有其他一些选项也可供使用。 - Mark Peschel
显示剩余2条评论

22
你可以使用 JAVA 7 的新 File API 来做到这一点。

代码示例:

public class FileWriter7 {
    public static void main(String[] args) throws IOException {
        List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
        String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
        writeSmallTextFile(lines, filepath);
    }

    private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, StandardCharsets.UTF_8);
    }
}

1
请注意,这个是最简单的解决方案,因为你只需要执行以下操作:Files.write(file.toPath(), content.getBytes()); 就能达到原问题的目标。 - Bill K

21
您可以使用Apache Commons中的FileUtils:FileUtils
import org.apache.commons.io.FileUtils;

final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);

1
如果你有多行代码,可以使用.writeLines()。在异常情况下,它会为你正确关闭所有内容,并且System.getProperty没有安全问题。如果没有commons库,这些都是一件麻烦的事情。 - Andrew

7

追加文件FileWriter(String fileName, boolean append)

try {   // this is for monitoring runtime Exception within the block 

        String content = "This is the content to write into file"; // content to write into the file

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here

        // if file doesnt exists, then create it
        if (!file.exists()) {   // checks whether the file is Exist or not
            file.createNewFile();   // here if file not exist new file created 
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
        BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
        bw.write(content); // write method is used to write the given content into the file
        bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect. 

        System.out.println("Done");

    } catch (IOException e) { // if any exception occurs it will catch
        e.printStackTrace();
    }

谢谢您的评论!现在图片更加清晰了! :) - Georgi Koemdzhiev
@BogGogo请查看更新后的答案,以在不擦除先前内容的情况下追加文件内容。FileWriter具有追加文件选项。该属性的默认值为false。 - newuser

4

像@Dilip Kumar所说的那样,Files.write()是一个简单的解决方案。我曾经使用过这种方式,直到遇到了一个问题:无法影响行分隔符(Unix/Windows)CR LF。

所以现在我使用Java 8中的流文件写入方式,可以让我即时操作内容。 :)

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());
}     

这样,我可以指定行分隔符或进行任何类似TRIM、Uppercase、过滤等的操作。

4

你的代码很简单。但是,我总是尝试进一步优化代码。这里有一个示例。

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
    bw.write("Hello, This is a test message");
    bw.close();
    }catch (FileNotFoundException ex) {
    System.out.println(ex.toString());
    }

我认为如果你那样做,你的FileWriter不会被关闭。不确定这是否重要。 - Shannon

3
在Java 11或更高版本中,可以使用java.nio.file.Files的writeString方法。
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content); 

有选项:

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

更多有关java.nio.file.FilesStandardOpenOption的文档。


3
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);

欢迎来到SO。请注意,仅包含代码的答案可能会因质量低而被删除。请参阅http://stackoverflow.com/help/how-to-answer。 - Uwe Allner
此外,请不要复制现有答案。 - james.garriss

-2
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));

IOUtils也可以在Java 8中轻松地写入/读取文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接