在 java 中将字符串写入文本文件
Write String to text-file in java
想将我从 JSON 解析为纯文本的一些信息保存到文件中,我还希望每次 运行 程序时都不会覆盖这些信息。它应该作为一个简单的错误记录系统工作。
到目前为止我试过这个:
FileWriter fileWriter = null;
File file = new File("/home/anderssinho/bitbucket/dblp-article-analyzer/logg.txt");
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
...
String content = "------------------------------------";
fileWriter = new FileWriter(file);
fileWriter.write(content);
//fileWriter.write(obj.getString("title"));
//fileWriter.write(obj.getString("creators"));
//fileWriter.write(article.GetElectronicEdition());
但是当我这样做时,我似乎一直在覆盖信息,而且我也无法保存我想从 JSON 数组中获取的信息。
我该怎么做才能使这项工作正常进行?
使用追加:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("logg.txt", true)));
看这个:
How to append text to an existing file in Java
FileWriter fooWriter = new FileWriter(myFoo, false);
// true 追加
// false 覆盖;
其中 myFoo 是文件名
看到这个link
你能详细说明一下吗?如果问题只是无法追加,那么您可以向 FileWriter 添加一个参数,说明它追加而不是从头开始写。
在此处检查构造函数:
public FileWriter(String fileName, boolean append) throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
想将我从 JSON 解析为纯文本的一些信息保存到文件中,我还希望每次 运行 程序时都不会覆盖这些信息。它应该作为一个简单的错误记录系统工作。
到目前为止我试过这个:
FileWriter fileWriter = null;
File file = new File("/home/anderssinho/bitbucket/dblp-article-analyzer/logg.txt");
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
...
String content = "------------------------------------";
fileWriter = new FileWriter(file);
fileWriter.write(content);
//fileWriter.write(obj.getString("title"));
//fileWriter.write(obj.getString("creators"));
//fileWriter.write(article.GetElectronicEdition());
但是当我这样做时,我似乎一直在覆盖信息,而且我也无法保存我想从 JSON 数组中获取的信息。
我该怎么做才能使这项工作正常进行?
使用追加:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("logg.txt", true)));
看这个: How to append text to an existing file in Java
FileWriter fooWriter = new FileWriter(myFoo, false);
// true 追加
// false 覆盖;
其中 myFoo 是文件名
看到这个link
你能详细说明一下吗?如果问题只是无法追加,那么您可以向 FileWriter 添加一个参数,说明它追加而不是从头开始写。
在此处检查构造函数:
public FileWriter(String fileName, boolean append) throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason