官术网_书友最值得收藏!

Writing ouput data

After the data is read and processed, we often want to put it back on disk. For text, this is usually done using the Writer objects.

Suppose we read the sentences from text.txt and we need to convert each line to uppercase and write them back to a new file output.txt; the most convenient way of writing the text data is via the PrintWriter class:

try (PrintWriter writer = new PrintWriter("output.txt", "UTF-8")) { 
for (String line : lines) {
String upperCase = line.toUpperCase(Locale.US);
writer.println(upperCase);
}
}

In Java NIO API, it would look like this:

Path output = Paths.get("output.txt"); 
try (BufferedWriter writer = Files.newBufferedWriter(output,
StandardCharsets.UTF_8)) {
for (String line : lines) {
String upperCase = line.toUpperCase(Locale.US);
writer.write(upperCase);
writer.newLine();
}
}

Both ways are correct and you should select the one that you prefer. However, it is important to remember to always include the encoding; otherwise, it may use some default values which are platform-dependent and sometimes arbitrary.

主站蜘蛛池模板: 资兴市| 滨州市| 兴业县| 阿巴嘎旗| 万山特区| 思南县| 通城县| 罗城| 沙坪坝区| 星座| 岑巩县| 宁波市| 循化| 临湘市| 吴桥县| 黔江区| 拉孜县| 逊克县| 罗江县| 墨江| 临沭县| 基隆市| 宁都县| 巴中市| 封丘县| 蒙自县| 曲麻莱县| 阳信县| 桂林市| 巴青县| 哈密市| 石家庄市| 大同县| 邹平县| 苏州市| 睢宁县| 锡林浩特市| 油尖旺区| 阿瓦提县| 共和县| 大渡口区|