如何将String写入文本文件?

use*_*445 7 java string text-files

我有一个String存储几个文件的处理结果.如何将该String写入项目中的.txt文件?我有另一个String变量,它是.txt文件的所需名称.

A B*_*A B 16

试试这个:

//Put this at the top of the file:
import java.io.*;
import java.util.*;

BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));

//Add this to write a string to a file
//
try {

    out.write("aString\nthis is a\nttest");  //Replace with the string 
                                             //you are trying to write
}
catch (IOException e)
{
    System.out.println("Exception ");

}
finally
{
    out.close();
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 6

你的意思是?

FileUtils.writeFile(new File(filename), textToWrite); 
Run Code Online (Sandbox Code Playgroud)

FileUtils在Commons IO中可用.


Pau*_*gas 5

使用基于字节的流创建的文件表示二进制格式的数据。使用基于字符的流创建的文件将数据表示为字符序列。文本文件可以由文本编辑器读取,而二进制文件则由将数据转换为人类可读格式的程序读取。

\n\n

FileReaderFileWriter执行基于字符的文件 I/O。

\n\n

如果您使用的是 Java 7,您可以使用try-with-resources大大缩短方法:

\n\n
import java.io.PrintWriter;\npublic class Main {\n    public static void main(String[] args) throws Exception {\n        String str = "\xe5\x86\x99\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2\xe5\x88\xb0\xe6\x96\x87\xe4\xbb\xb6"; // Chinese-character string\n        try (PrintWriter out = new PrintWriter("output.txt", "UTF-8")) {\n            out.write(str);\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

可以使用Java\xe2\x80\x99stry-with-resources语句自动关闭资源(不再需要时必须关闭的对象)。您应该考虑资源类必须实现该java.lang.AutoCloseable接口或其java.lang.Closeable子接口。

\n