在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
如果希望将字符串中的回车字符保留在文件中下面是一个代码示例:
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);
}
});
其他回答
我认为最好的方法是使用File.write(路径路径,Iterable<?extends CharSequence>行,OpenOption…options):
String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));
参见javadoc:
将文本行写入文件。每一行都是一个字符序列按顺序写入文件,每行以平台的行分隔符,由系统属性定义line.separator。字符使用指定的字符集。options参数指定如何创建或打开文件。如果不存在任何选项,则该方法的工作方式与CREATE,存在TRUNCATE_EXISTING和WRITE选项。换句话说打开文件进行写入,如果文件不存在则创建文件,或最初将现有的常规文件截断为0的大小。这个方法确保文件在所有行都已关闭时关闭写入(或引发I/O错误或其他运行时异常)。如果如果发生I/O错误,则可能会在文件创建或或者在一些字节被写入文件之后。
请注意。我看到人们已经用Java内置的Files.write进行了回答,但我的回答中有一个特别之处,似乎没有人提到,那就是重载版本的方法,它采用了CharSequence的Iterable(即String),而不是byte[]数组,因此不需要text.getBytes(),我认为这有点干净。
看看Java文件API
快速示例:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
Apache Commons IO包含一些很好的方法,特别是FileUtils包含以下方法:
static void writeStringToFile(File file, String data, Charset charset)
它允许您在一个方法调用中将文本写入文件:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));
您可能还需要考虑指定文件的编码。
使用Apache Commons IO api。它很简单
使用API作为
FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");
Maven依赖项
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
使用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);
}