简体   繁体   中英

For loop doesn't seem to be executing

When I run this only one line is written to the file even when the ArrayList hash has more than one value.

I have tried removing fileWriter.close but then nothing is written to the file.

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);
    }
}

I would like this to write each value of the array to its own line in the file.

You are continuously opening and closing the file; you should open it once before your loop (and close it once after). However, it is not necessary to manually close the file at all if you use the try-with-Resources close statement (which is what I would prefer ). And a newline is \\n (but that's also OS specific) so I would use System.lineSeparator() . Finally, there is no reason to use an explicit array index here so I would use a for-each loop . Like,

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);
}

That's because you keep overwriting the same file. Every time you execute one iteration of the loop, you open the file and overwrite its contents.

Move your for loop inside the try/catch between the opening and closing of the file as follows:

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);
}

use fileWriter = new FileWriter(OutputPath, true); . This will make append to true. So your file content will not be overridden in the for loop

or move the fileWriter = new FileWriter(OutputPath); out from the for loop

The for loop is executed and each time you overwrite the content of the file.

You should use append mode when opening a file stream. Otherwise you will overwrite all lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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