1 回答
TA贡献1797条经验 获得超6个赞
使用 FileWriter 写入文件
public static void main(String[] args) {
String[] inputs = new String[] {"input-1","input-2","input-3"};
File outputFile = new File("output.txt");
try(FileWriter writer = new FileWriter(outputFile)){
for(String input:inputs) {
writer.write(input);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
使用 BufferedWriter 逐行写入文件
public static void main(String[] args) {
String[] input = new String[] {"input-1","input-2","input-3"};
File outputFile = new File("output-buffer.txt");
try(BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))){
for(String inputLine:input) {
writer.write(inputLine);
writer.newLine();
}
} catch (IOException e1) {
System.out.println(e.getMessage());
}
}
从 java7 开始,您可以使用Files来编写
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
添加回答
举报