在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
在Java 7中,您可以执行以下操作:
String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());
这里有更多信息:http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
其他回答
使用org.apache.mons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
在Java11中,Java.nio.file.Files类被两个新的实用程序方法扩展,以将字符串写入文件。第一种方法(请参阅此处的JavaDoc)使用UTF-8字符集作为默认值:
Files.writeString(Path.of("my", "path"), "My String");
第二种方法(参见此处的JavaDoc)允许指定单个字符集:
Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);
这两种方法都有一个可选的Varargs参数,用于设置文件处理选项(请参阅此处的JavaDoc)。以下示例将创建一个不存在的文件或将字符串附加到现有文件:
Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
我的方法基于流,因为在所有Android版本上运行,并且需要有效的资源,如URL/URI,欢迎任何建议。
就目前而言,流(InputStream和OutputStream)传输二进制数据,当开发人员将字符串写入流时,必须首先将其转换为字节,或者换句话说,对其进行编码。
public boolean writeStringToFile(File file, String string, Charset charset) {
if (file == null) return false;
if (string == null) return false;
return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}
public boolean writeBytesToFile(File file, byte[] data) {
if (file == null) return false;
if (data == null) return false;
FileOutputStream fos;
BufferedOutputStream bos;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data, 0, data.length);
bos.flush();
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return false;
}
return true;
}
看看Java文件API
快速示例:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(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
}