- Mastering Java for Data Science
- Alexey Grigorev
- 161字
- 2021-07-02 23:44:34
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.
推薦閱讀
- 計算機組成原理與接口技術:基于MIPS架構實驗教程(第2版)
- 云計算環境下的信息資源集成與服務
- Spark大數據分析實戰
- 商業分析思維與實踐:用數據分析解決商業問題
- iOS and OS X Network Programming Cookbook
- 跟老男孩學Linux運維:MySQL入門與提高實踐
- Lego Mindstorms EV3 Essentials
- PostgreSQL指南:內幕探索
- Construct 2 Game Development by Example
- HikariCP連接池實戰
- 跨領域信息交換方法與技術(第二版)
- 聯動Oracle:設計思想、架構實現與AWR報告
- Doris實時數倉實戰
- 中國云存儲發展報告
- 大數據時代系列(套裝9冊)