在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
如果您只是输出文本,而不是任何二进制数据,则以下操作将起作用:
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。
其他回答
使用Java 7:
public static void writeToFile(String text, String targetFilePath) throws IOException
{
Path targetPath = Paths.get(targetFilePath);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}
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。
我的方法基于流,因为在所有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);
}
使用org.apache.mons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());