[英]How to output file as terminal shows in JAVA? (Java 14 Intellij IDEA)
我需要讀取輸入 txt 文件並格式化打印作為輸出文件。 由於我通過多個語句在終端中輸出它,因此 fileOutput.println() 效果不佳。 輸出文件為空。 有沒有其他方法可以像終端顯示的那樣輸出文件? 謝謝。
輸入的txt文件是:
我的終端按預期顯示格式化的打印:
我的代碼如下:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws IOException {
String[] words; // array of strings
Scanner fileInput = new Scanner(new File("/Users/transactions_input.txt"));
File outputFile = new File("/Users/transactions_output.txt");
PrintWriter fileOutput = new PrintWriter(outputFile);
while (fileInput.hasNext()) {
// read a line, split it with comma as a delimiter, and store them as an array
words = fileInput.nextLine().split(",");
// formatted print
if (words.length == 2) {
System.out.println(words[0] + "," + words[1]);
}
else if (words.length == 4) {
System.out.println(words[0] + "," + words[1]);
System.out.println(words[0] + "," + words[2]);
System.out.println(words[0] + "," + words[3]);
}
else if (words.length == 3) {
System.out.println(words[0] + "," + words[1]);
System.out.println(words[0] + "," + words[2]);
}
fileOutput.println();
}
}
}
您的代碼將格式化的行打印到stdout
,而只有一個語句打印到所需的輸出文件。
用fileOutput.println()
替換對System.out.println()
的調用。
例如: fileOutput.println(words[0] + "," + words[1]);
而不是: System.out.println(words[0] + "," + words[1]);
請記住關閉PrintWriter
或使用try-with-resources 。
或者,您可以打印到stdout
並在執行程序時使用輸出重定向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.