你可以尝试做这样的事情:
public void write(final File file, final List<String> lines) throws IOException{
final BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //new FileWriter(file, true) if you want to append the file (default is false)
for(final String line : lines){
writer.write(line);
writer.newLine();
}
writer.flush();
writer.close();
}
如果您使用的是 Java 8,请随意尝试使用 lambda:
public void write(final File file, final List<String> lines) throws IOException{
final BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //new FileWriter(file, true) if you want to append the file (default is false)
lines.forEach(
l -> {
try{
writer.write(l);
writer.newLine();
}catch(IOException ex){
ex.printStackTrace();
}
}
);
writer.flush();
writer.close();
}
对于使用,你可以试试这个:
write(new File(fileName), Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4"));