Search code examples
javaarraysfileoutputstreamprintstream

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!


Solution

  • 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.