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

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.

主站蜘蛛池模板: 黄平县| 东阳市| 疏勒县| 唐海县| 荆州市| 榆社县| 崇左市| 阜平县| 新沂市| 海林市| 岳西县| 荆州市| 象州县| 略阳县| 二连浩特市| 镇巴县| 平泉县| 扬中市| 金阳县| 安乡县| 石门县| 宁陵县| 珠海市| 日照市| 图木舒克市| 辽阳县| 馆陶县| 通化县| 来安县| 泽普县| 崇义县| 新平| 双柏县| 临海市| 晋州市| 墨江| 德庆县| 达拉特旗| 沙坪坝区| 陆丰市| 阿拉善盟|