bufferedwriter 与系统输出 println

buffered writer vs. sys out print

我是 java 的新手,想了解这不起作用的原因。为什么 sys out 打印工作完美,但缓冲的 writer 却不行?我只是想了解两者之间的区别/

//print the input matrix to the user

System.out.println("Matrix read: ");
System.out.println("------------------" +
                   "---------------------");
for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
        System.out.printf("%5d ", a[i][j]);
        bw.write(a[i][j]);
        bw.flush();
    }

    //print a blank line
    System.out.println();

缓冲写入器输出(来自 .txt 文件):

     The Determinant is: 5
     The Determinant is: 3
     �The Determinant is: 64
�   ��  ���The Determinant is: 270
������   ���The Determinant is: 0
��������    ����The Determinant is: 270
������    The Determinant is: 0
    The Determinant is: 0

Sys out打印输出:

Matrix read: 
---------------------------------------
    5 
---------------------------------------
Matrix read: 
---------------------------------------
    2     3 
---------------------------------------
    5     9 
---------------------------------------
Matrix read: 
---------------------------------------
    3    -2     4 
---------------------------------------
   -1     5     2 
---------------------------------------
   -3     6     4 
---------------------------------------

write()你写字节。在您的第一个矩阵中,您有数值 5。如果您使用 write(5),您将写入字节值 5,它是您正在使用的文本编辑器以某种方式显示的不可打印字符。如果您使用 hexdump 实用程序,您会发现它实际上是字节 5.

对于 printf 函数,您需要五个格式字符串,您可以使用它告诉它如何格式化参数,即数字 5。这里的%5d表示将数字格式化为宽度至少为5的字符串,并在前面填充space。然后是 space 之后。

如果您想对缓冲写入器产生相同的效果,请将其包装在 PrintWriter 中并使用相同的 printf 方法和参数,您将获得相同的结果。如果您只想在 BufferedWriter 中将数字格式化为字符串,则必须在编写之前将数字转换为字符串,例如。 G。使用 Integer.toString(5).getBytes() 然后使用相应的 write() 方法写入此字节数组。

System.out是一个PrintStream;要获得相同的行为,请尝试使用用您的文件名实例化的 PrintStream(或 PrintWriter)并使用 print/println/format 方法。

BufferedWriter.write(int c) 方法将 int 参数解释为一个字符,因此如果您传递 32,它将打印一个 space 字符;这很可能不是您想要的。

而不是用

写一个原始的int
bw.write(a[i][j]);

(如果你想把同样的东西写到你的BufferedWriter)你需要用同样的方式格式化你的输出。你可以使用 String.format 之类的东西

bw.write(String.format("%5d ", a[i][j]));

并且,如果您希望它相同,则需要添加一个新行(您调用 System.out.println 的地方),例如

bw.write(System.lineSeparator());