- 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.
推薦閱讀
- 數據要素安全流通
- 數據產品經理高效學習手冊:產品設計、技術常識與機器學習
- 分布式數據庫系統:大數據時代新型數據庫技術(第3版)
- 數據要素五論:信息、權屬、價值、安全、交易
- Python數據分析:基于Plotly的動態可視化繪圖
- Spark大數據編程實用教程
- ZeroMQ
- MATLAB Graphics and Data Visualization Cookbook
- 高維數據分析預處理技術
- 數據科學工程實踐:用戶行為分析與建模、A/B實驗、SQLFlow
- 菜鳥學SPSS數據分析
- 機器學習:實用案例解析
- 企業大數據處理:Spark、Druid、Flume與Kafka應用實踐
- Unity Game Development Blueprints
- 一本書讀懂大數據