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

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.

主站蜘蛛池模板: 中阳县| 龙州县| 绿春县| 高台县| 准格尔旗| 重庆市| 长白| 西和县| 东兴市| 亳州市| 宝应县| 三都| 鹤山市| 星子县| 上杭县| 西和县| 长海县| 吉隆县| 保山市| 宿松县| 手游| 九龙县| 论坛| 会理县| 洮南市| 汉川市| 蒙自县| 大丰市| 凌云县| 聂拉木县| 综艺| 塘沽区| 出国| 石阡县| 嘉黎县| 仁寿县| 盐池县| 长治县| 双辽市| 金湖县| 永嘉县|