在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
使用Apache Commons IO中的FileUtils.writeStringToFile()。无需重新发明这个轮子。
其他回答
如果您需要基于一个字符串创建文本文件:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class StringWriteSample {
public static void main(String[] args) {
String text = "This is text to be saved in file";
try {
Files.write(Paths.get("my-file.txt"), text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果希望将字符串中的回车字符保留在文件中下面是一个代码示例:
jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
orderButton = new JButton("Execute");
textArea = new JTextArea();
...
// String captured from JTextArea()
orderButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// When Execute button is pressed
String tempQuery = textArea.getText();
tempQuery = tempQuery.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
out.print(tempQuery);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tempQuery);
}
});
我的方法基于流,因为在所有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;
}
最好在finally块中关闭writer/outputstream,以防发生意外
finally{
if(writer != null){
try{
writer.flush();
writer.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
我已经发布了一个库,它保存文件,并且只使用一行代码处理所有内容,您可以在这里找到它及其文档
Github存储库
你的问题答案很简单
String path = FileSaver
.get()
.save(string.getBytes(),"file.txt");