在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
使用org.apache.mons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
其他回答
使用这个,它非常易读:
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
看看Java文件API
快速示例:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
我的方法基于流,因为在所有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;
}
import java.io.*;
private void stringToFile( String text, String fileName )
{
try
{
File file = new File( fileName );
// 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( text );
bw.close( );
//System.out.println("Done writing to " + fileName); //For testing
}
catch( IOException e )
{
System.out.println("Error: " + e);
e.printStackTrace( );
}
} //End method stringToFile
您可以将此方法插入到类中。如果在具有主方法的类中使用此方法,请通过添加静态关键字将该类更改为static。无论哪种方式,您都需要导入java.io.*以使其正常工作,否则将无法识别File、FileWriter和BufferedWriter。
在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);