【问题标题】:How can I read a String with System.in using a InputStream or DataInputStream如何使用 InputStream 或 DataInputStream 读取带有 System.in 的字符串
【发布时间】:2021-07-23 14:28:13
【问题描述】:

我正在尝试使用 InputStream o DataInputStream 读取带有 System.in 的字符串,也许我可以使用 BufferedInputStream,但我不知道如何使用它,我正在寻找但我不明白它是如何使用的有效,我正在尝试做这样的事情。

import java.io.*;
public class Exer10 {
    public static void main(String[] args) throws IOException {
        InputStream is = System.in;
        DataInputStream dis = new DataInputStream(is);
        try {
            while (true){
                dis.readChar();
            }
        } catch (EOFException e){
            
        }
    }
}

这里的问题是我在 System.in 中循环,因为方法“readChar”在循环中,但是如果我将“dis.readChar()”放在另一个位置,这只会返回一个字节,你能帮帮我吗?

我找到的解决方案是我可以将它放在一个字节数组中,但这并不能解决任何问题,因为如果我这样做,文件必须始终具有相同的长度,而这个长度不能被移动。像这样的:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Exer10 {
    public static void main(String[] args) throws IOException {
        InputStream is = System.in;
        DataInputStream dis = new DataInputStream(is);
        byte[] bytes = new byte[10];
        dis.read(bytes);
    }
}

【问题讨论】:

  • 只需使用:Scanner sc = new Scanner(System.in); while () { String line = sc.nextLine(); .... } sc.close();
  • 您为什么不按照DataInputStream.readLine() 上的JavaDoc 的建议进行操作,并将其包装在BufferedReader 中并使用该类'readLine(),直到您不再获得更多数据?然后只需将您读到的字符串合并为一个,例如通过将它们附加到StringBuilder。当我们在做的时候:你到底想做什么?从命令行读取输入?

标签: java inputstream fileinputstream datainputstream


【解决方案1】:

如果有一个字节,readChar 将只返回一个字节。您可以解决的方法如下:

  1. 检查流中是否有一些数据可用(可用应返回非空字节数)
  2. 用现有内容填充一个新的字节数组(后来转换为字符串):with read(byte[] bytes)

然后你可以使用提取的数据:)

    public static void main(String[] args) {
        InputStream is = System.in;
        DataInputStream dis = new DataInputStream(is);
        try {
            while (true) {
                int count = dis.available();
                if (count > 0) {
                    // Create byte array
                    byte[] bytes = new byte[count];
    
                    // Read data into byte array
                    int bytesCount = dis.read(bytes);
    
                    System.out.println("Result: "+ new String(bytes));
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }

来源:

javadoc:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/DataInputStream.html 例如:https://www.geeksforgeeks.org/datainputstream-read-method-in-java-with-examples/#:~:text=read(byte%5B%5D%20b)%20method,data%20is%20available%20to%20read

使用 Scanner 确实更容易实现:

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            System.out.println("input: "+sc.nextLine());            
        }
    }

【讨论】:

  • 非常感谢,这对我来说是新的,你帮助我更好地理解它:))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 2010-09-23
相关资源
最近更新 更多