2

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!

3 Answers3

1

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.

Adam Evans
  • 2,072
  • 1
  • 20
  • 29
  • Wow, I feel stupid as hell! Thanks so much!! When it lets me accept an answer in 10 minutes, I will accept this as the answer... –  Dec 11 '15 at 00:13
0

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();
}
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
0

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.

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
  • Yea I know about that, but I'm looking for something different. Thank you tho! –  Dec 11 '15 at 00:14