Java 将数字的控制台输出写入文本文件

Java 将数字的控制台输出写入文本文件,java,arrays,fileoutputstream,printstream,Java,Arrays,Fileoutputstream,Printstream,快速提问,我不知道我错过了什么。如果一行中有9个数字的控制台输出,总共有9行,那么如何将精确的输出写入外部文本文件,使其在文本文件中看起来相同 假设控制台如下所示: 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

快速提问,我不知道我错过了什么。如果一行中有9个数字的控制台输出,总共有9行,那么如何将精确的输出写入外部文本文件,使其在文本文件中看起来相同

假设控制台如下所示:

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
控制台输出存储在一个名为“myArray”的数组变量中,我如何将其写入一个文本文件,使其看起来像这样(或用逗号分隔)

到目前为止,我有:

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] + " ");
  }
}
File solutionFile=新文件(“output.txt”);
FileOutputStream=新的FileOutputStream(solutionFile);
PrintStream writeOut=新的PrintStream(流);
系统放样(注销);
对于(int行=0;行<9;行++){
for(int columns=0;columns<9;columns++){
System.out.println(myArray[行][列]+“”);
}
}

当它写入文件时,每个数字都放在自己的行上。有可能的帮助吗?谢谢大家!

不要将print语句设置为
println
,只设置为
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
}
for(int行=0;行<9;行++){
for(int columns=0;columns<9;columns++){
System.out.print(myArray[rows][columns]+“”);//保持在同一行上打印
}
System.out.println();//转到下一行
}
您可以做的另一件事是I/O重定向。如果通过终端或命令提示符运行程序,则可以键入
java MyProgram>outputFile.txt
将控制台输出重定向到
outputFile.txt
,而不是它通常所在的位置。

使用以下代码(而不是println使用just pring并在第二秒后调用println()

File solutionFile=新文件(“output.txt”);
FileOutputStream=新的FileOutputStream(solutionFile);
PrintStream writeOut=新的PrintStream(流);
系统放样(注销);
对于(int行=0;行<9;行++){
for(int columns=0;columns<9;columns++){
System.out.print(myArray[行][列]+“”);
}
System.out.println();
}

我知道这可能不是您需要的,但为了让您了解其他方法,我把它放在这里。另一个答案就是你所需要的

如果您使用命令行执行java代码,则可以通过如下方式运行代码将STDOUT重定向到文件:
javamain>output.txt


您还可以重定向STDIN:
javamainoutput.txt

哇,我觉得自己太蠢了!非常感谢!!当它让我在10分钟内接受一个答案时,我会接受这个答案……是的,我知道,但我在寻找不同的答案。谢谢你,tho!
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();
}