Java如何在JDK 7中编写文本文件?
在JDK7我们可以写出从所有行List的String成使用一个文件Files.write()方法。我们需要提供Path要写入的文件的List,字符串和字符集的。每行都是一个char序列,并按顺序写入文件,每行由平台的行分隔符终止。
让我们看看下面的代码片段:
package org.nhooo.example.io;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class WriteTextFile {
public static void main(String[] args) {
Path file = Paths.get("D:/resources/data.txt");
List<String> lines = new ArrayList<>();
lines.add("Lorem Ipsum is simply dummy text of the printing ");
lines.add("and typesetting industry. Lorem Ipsum has been the ");
lines.add("industry's standard dummy text ever since the 1500s, ");
lines.add("when an unknown printer took a galley of type and ");
lines.add("scrambled it to make a type specimen book.");
try {
//将几行文字写入文件。
Files.write(file, lines, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
}
}此代码段将data.txt在该resources文件夹下创建一个名为的文件。在尝试运行代码之前,请确保该文件夹存在。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短