简体   繁体   中英

Write console output of numbers to text file

quick question, I don't know what I'm missing here. If I have a console output of 9 numbers in a row, and 9 total rows, how would I go about writing that exact output to an external text file, so it looks the same way in the text file.

Assuming the console looks like this:

2 4 5 1 9 3 6 8 7 
9 7 6 2 5 8 4 1 3 
1 8 3 7 4 6 9 2 5 
8 5 2 3 1 9 7 4 6 
3 1 9 4 6 7 8 5 2 
7 6 4 5 8 2 3 9 1 
4 3 8 6 2 5 1 7 9 
5 9 7 8 3 1 2 6 4 
6 2 1 9 7 4 5 3 8

And that console output is stored in an array variable named "myArray" How would I write it to a text file so it looks just like that (or separated by commas)

So far I have this:

File solutionFile = new File("output.txt");
FileOutputStream stream = new FileOutputStream(solutionFile);
PrintStream writeOut = new PrintStream(stream);
System.setOut(writeOut);

for (int rows = 0; rows < 9; rows++) {
  for (int columns = 0; columns < 9; columns++) {
    System.out.println(myArray[rows][columns] + " ");
  }
}

When it writes to the file, each number is placed on its own line. Any assistance possible? Thank you!

Don't make the print statement a println , just a print .

for (int rows = 0; rows < 9; rows++) {
  for (int columns = 0; columns < 9; columns++) {
    System.out.print(myArray[rows][columns] + " ");    //keep printing on the same line
  }
  System.out.println();    //go to the next line
}

Another thing you could do is I/O redirection. If you run the program via terminal or command prompt, you can type java MyProgram > outputFile.txt . The > redirects the console output to go to outputFile.txt instead of where it normally goes.

Use following code (instead of println use just pring and call println() after second for)

File solutionFile = new File("output.txt");
FileOutputStream stream = new FileOutputStream(solutionFile);
PrintStream writeOut = new PrintStream(stream);
System.setOut(writeOut);

for (int rows = 0; rows < 9; rows++) {
  for (int columns = 0; columns < 9; columns++) {
    System.out.print(myArray[rows][columns] + " ");
  }
  System.out.println();
}

I know this is probably not something you need, but just to give you an idea about the other ways to do it, I put it here. The other answer is pretty much what you need.

If you are using command line to execute your java code, you can redirect STDOUT to a file by running your code like this: java Main > output.txt

You can also redirect STDIN: java Main < input.txt > output.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM