我在弄清楚如何将字符串拆分为多个文件时遇到了问题。目前我应该获得两个带有JSON数据的文件。下面的代码写入第一个文件,但第二个文件留空。有什么想法吗?
public void splitFile(List<String> results) throws IOException {
int name = 0;
for (int i=0; i<results.size(); i ++) {
write = new FileWriter("/home/tom/files/"+ name +".json");
out = new BufferedWriter(write);
out.write(results.get(i));
if (results.get(i).startsWith("}")) {
name++;
}
}
}
编辑:它从{
开始分割,因为它表示JSON文档的结尾。
答案 0 :(得分:1)
我会在每个完成的写序列后关闭你的缓冲写入器。即,在每次迭代循环之后,将write
分配给新的FileWriter()
。
关闭BufferedWriter
将关闭基础FileWriter
,因此强制刷新写入磁盘的数据。
注意:如果你在每个循环中使用一个不同的FileWriter
,那么我会将该变量调整到该内循环,例如。
FileWriter write = new FileWriter("/home/tom/files/"+ name +".json");
BufferedWriter
同样如此。实际上你可以写:
BufferedWriter outer = new BufferedWriter(new FileWriter(...
并且只处理outer
。
答案 1 :(得分:1)
加强削减控制
更进一步:
write = new FileWriter("/home/tom/files/"+ name +".json");
out = new BufferedWriter(write);
和此:
name++;
检查是否开始,而不是结束
检查以{
开头的行,并执行这三行以打开文件。
请记得关闭并刷新
如果它不是第一行(i > 0
),则关闭最后一个作者(write.close();
)。
关闭上次打开的作家
if (!results.isEmpty())
out.close();
<强>结果强>
看起来应该是这样的:
public void splitFile(List<String> results) throws IOException {
int name = 0;
BufferedWriter out = null;
for (int i=0; i<results.size(); i ++) {
String line = results.get(i);
if (line.startsWith("{")) {
if (out != null) // it's not the first
out.close(); // tell buffered it's going to close, it makes it flush
FileWriter writer = new FileWriter("/home/tom/files/"+ name +".json");
out = new BufferedWriter(writer);
name++;
}
if (out == null)
throw new IllegalArgumentException("first line doesn't start with {");
out.write(line);
}
if (out != null) // there was at least one file
out.close();
}
答案 2 :(得分:0)
请尝试以下代码..
public void splitFile(List<String> results) throws IOException {
int name = 0;
for (int i = 0; i < results.size(); i++) {
write = new FileWriter("/home/tom/files/" + name + ".json");
out = new BufferedWriter(write);
out.write(results.get(i));
out.flush();
out.close(); // you have to close your stream every time in your case.
if (results.get(i).startsWith("}")) {
name++;
}
}
}