在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
我倾向于尽可能依赖于库来进行这种操作。这使我不太可能意外地忽略一个重要的步骤(如上面狼鹬犯的错误)。上面建议了一些库,但我最喜欢的是GoogleGuava。Guava有一个名为Files的类,非常适合此任务:
// 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
}
其他回答
如果您只是输出文本,而不是任何二进制数据,则以下操作将起作用:
PrintWriter out = new PrintWriter("filename.txt");
然后,将String写入其中,就像写入任何输出流一样:
out.println(text);
您将一如既往地需要异常处理。写完后一定要调用.close()。
如果您使用的是Java 7或更高版本,则可以使用“try with resources语句”,该语句将在完成PrintStream(即退出块)后自动关闭PrintStream,如下所示:
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
您仍然需要像以前一样显式抛出java.io.FileNotFoundException。
使用Apache Commons IO中的FileUtils.writeStringToFile()。无需重新发明这个轮子。
你可以这样做:
import java.io.*;
import java.util.*;
class WriteText
{
public static void main(String[] args)
{
try {
String text = "Your sample content to save in a text file.";
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(text);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
return ;
}
};
使用org.apache.mons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
看看Java文件API
快速示例:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}