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)
你的意思是?
FileUtils.writeFile(new File(filename), textToWrite);
Run Code Online (Sandbox Code Playgroud)
FileUtils在Commons IO中可用.
使用基于字节的流创建的文件表示二进制格式的数据。使用基于字符的流创建的文件将数据表示为字符序列。文本文件可以由文本编辑器读取,而二进制文件则由将数据转换为人类可读格式的程序读取。
\n\n类FileReader
并FileWriter
执行基于字符的文件 I/O。
如果您使用的是 Java 7,您可以使用try-with-resources
大大缩短方法:
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
子接口。
归档时间: |
|
查看次数: |
47134 次 |
最近记录: |