简体   繁体   English

DataOutputStream中的System.out未在控制台上打印

[英]System.out in DataOutputStream is not printing on the console

I am trying the following code using the DataOutputStream. 我正在使用DataOutputStream尝试以下代码。 The OutputStream passed to the DataOutputStream is not printing anything. 传递给DataOutputStream的OutputStream不打印任何内容。 Please see my below code and pllease tell me anything wrong in this code. 请看下面的代码,请告诉我这段代码有什么问题。

public class DataStreamsExample {
public static void main(String[] args) throws IOException {
    DataInputStream dis = new DataInputStream(System.in);
    System.out.println("Enter the First Number");
    int i = dis.readInt();
    System.out.println("Enter the Second Numebr");
    int j= dis.readInt();
    int total = i+j;
    DataOutputStream dos = new DataOutputStream(System.out);
    dos.writeInt(total);

}

} }

Why are you using data output streams? 你为什么使用数据输出流? Can't you use a Scanner for reading input? 你不能用Scanner读取输入吗?

Calling dos.flush() will print out your result though. 调用dos.flush()会打印出你的结果。

OutputStream is fundamentally a binary construct. OutputStream基本上是一个二进制构造。 If you want to write text data (eg from the console) you should use a Writer of some description. 如果要编写文本数据(例如从控制台),则应使用某些描述的Writer。 To convert an OutputStream into a Writer, use OutputStreamWriter . 要将OutputStream转换为Writer,请使用OutputStreamWriter Then create a PrintWriter around the Writer, and you can read a line using PrintWriter .println(). 然后在Writer周围创建一个PrintWriter ,您可以使用PrintWriter .println()读取一行。 You can replace follow line 您可以替换以下行

DataOutputStream out = new DataOutputStream(out);

into this 进入这个

PrintWriter out = new PrintWriter(new OutputStreamWriter(out));

The character encoding can then be explicitly specified in the constructor of OutputStreamWriter. 然后可以在OutputStreamWriter的构造函数中显式指定字符编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM