在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
只是在我的项目中做了类似的事情。使用FileWriter将简化部分工作。在这里你可以找到很好的教程。
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
其他回答
看看Java文件API
快速示例:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
使用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.FileWriter;
public void saveToFile(String data, String filename) {
try (
FileWriter fw = new FileWriter(filename)) {
fw.write(data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
我已经发布了一个库,它保存文件,并且只使用一行代码处理所有内容,您可以在这里找到它及其文档
Github存储库
你的问题答案很简单
String path = FileSaver
.get()
.save(string.getBytes(),"file.txt");
最好在finally块中关闭writer/outputstream,以防发生意外
finally{
if(writer != null){
try{
writer.flush();
writer.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}