正确地用Java写入stdout

时间:2016-02-09 21:07:22

标签: java

我正在用Java中的unix编写一个非常简单的cat函数实现。

public class Cat {
    public static void main(String[] args) {
            try{

                int ch;
                BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
                while ((ch = System.in.read ()) != -1)
                    log.write((char) ch);
                    log.flush();

            }catch(IOException io){
                io.printStackTrace();
            }
    }
}

当我传递这样的文本文件输入时,我得到:

$cat hello.txt | java Cat

this is
the second line
no jk the third

然而,当我传入另一种类似jpg的文件时,它无法正常复制。我将传递一个jpg,但当我尝试打开它时,我得到的错误是:

Error interpreting JPEG image file (Not a JPEG file: starts with 0xc3 0xbf)

当涉及IO相关的东西时,我很天真,所以我无法弄清楚出了什么问题?我不是像我想的那样给stdout写信吗?

1 个答案:

答案 0 :(得分:0)

您在bytechar之间感到困惑,以及用于读取和写入它们的相应类(当您不熟悉Java IO时这很容易):

  • byte是一个字节(8位)。您使用InputStream阅读,并使用OutputStream
  • 撰写
  • char是一个双字节无符号整数(16位)。您使用Reader阅读它们并使用Writer
  • 进行书写

System.inInputStream,因此您实际上是从byte读取char,而不是System.in.read(); int返回int ch; while ((ch = System.in.read ()) != -1) System.out.write(ch); System.out.flush(); // Optional, it will flush upon JVM termination anyway. 的唯一原因是它可以指示没有字节可供读取。

因此,以下内容应该有效:

byte

请注意,JPEG由char s组成,而不是char s。因此,如果您使用类来编写childViewController来编写JPEG文件的内容,那么内容可能就是垃圾。