繁体   English   中英

For循环似乎没有执行

[英]For loop doesn't seem to be executing

当我运行它时,即使ArrayList散列具有多个值,也只会向文件写入一行。

我已经尝试删除fileWriter.close但是没有任何内容写入该文件。

for (int i = 0; i < hash.size(); i++) {
    String fileContent = hash.get(i);
    FileWriter fileWriter;
    try {
        fileWriter = new FileWriter(OutputPath);
        fileWriter.write(fileContent);
        fileWriter.write("/n");
        fileWriter.close();
    } catch (IOException ex) {
        Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
    }
}

我希望这会将数组的每个值写入文件中自己的行。

您不断打开和关闭文件; 你应该在你的循环之前打开它一次(然后关闭它一次)。 但是,如果使用try-with-Resources close语句 (这是我更喜欢的 ),则根本不需要手动关闭文件。 换行符是\\n (但这也是特定于操作系统的)所以我会使用System.lineSeparator() 最后,没有理由在这里使用显式数组索引,因此我将使用for-each循环 喜欢,

try (FileWriter fileWriter = new FileWriter(OutputPath)) {
  for (String fileContent : hash) {
    fileWriter.write(fileContent);
    fileWriter.write(System.lineSeparator());
  }
} catch (IOException ex) {
    Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}

那是因为你一直在覆盖同一个文件。 每次执行循环的一次迭代时,都会打开文件并覆盖其内容。

在文件的打开和关闭之间移动try环境中的for循环,如下所示:

FileWriter fileWriter;
try {
    // open the file once
    fileWriter = new FileWriter(OutputPath);

    // loop through your items, writing each one to the file
    for (int i = 0; i < hash.size(); i++) {
        String fileContent = hash.get(i);
        fileWriter.write(fileContent);
        fileWriter.write("/n");
    }

    // close the file once
    fileWriter.close();
} catch (IOException ex) {   
    Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}

使用fileWriter = new FileWriter(OutputPath, true); 这将使得追加到真实。 因此,您的文件内容不会在for循环中被覆盖

或者移动fileWriter = new FileWriter(OutputPath); for loop

每次覆盖文件内容时都会执行for循环。

打开文件流时应使用追加模式。 否则你将覆盖所有行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM