Issue
I need to read an input txt file and formatted print as an output file. Since I output it in terminal through multiple statements, fileOutput.println() doesn't work well. The output file is empty. Is there any other way I can output the file as the terminal shows? Thanks.
The input txt file is:
My terminal shows the formatted print as expected:
My code is as follow:
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();
}
}
}
Solution
Your code prints the formatted lines to stdout
, while only one statement prints to the desired output file.
Replace the calls to System.out.println()
with fileOutput.println()
.
E.g.:
fileOutput.println(words[0] + "," + words[1]);
instead of:
System.out.println(words[0] + "," + words[1]);
Remember to close the PrintWriter
or use try-with-resources.
Alternatively, you can print to stdout
and use output redirection when executing the program.
Answered By - Asaf Amnony Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.