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

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.

主站蜘蛛池模板: 塘沽区| 高平市| 凌海市| 九台市| 新竹县| 大埔区| 肇庆市| 辽源市| 平顺县| 蒙山县| 合作市| 万安县| 瓮安县| 嘉兴市| 仁怀市| 房产| 舞钢市| 会东县| 社旗县| 澜沧| 阳新县| 团风县| 冕宁县| 德格县| 广南县| 博白县| 宜君县| 双桥区| 金沙县| 武陟县| 江阴市| 阿荣旗| 邢台市| 临武县| 柘荣县| 永安市| 大兴区| 全州县| 德化县| 永和县| 伊宁市|