簡體   English   中英

如何使用 InputStream 或 DataInputStream 讀取帶有 System.in 的字符串

[英]How can I read a String with System.in using a InputStream or DataInputStream

我正在嘗試使用 InputStream o DataInputStream 使用 System.in 讀取字符串,也許我可以使用 BufferedInputStream,但我不知道如何使用它,我正在尋找 bu 我不明白它是如何工作的,我我正在嘗試做這樣的事情。

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()”放在另一個 position 中,這只返回一個字節,你能幫幫我嗎請問我?

我找到的解決方案是我可以將它放在一個字節數組中,但這並不能解決任何問題,因為如果我這樣做,文件必須始終具有相同的長度,並且這個長度不能移動。 像這樣的東西:

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);
    }
}

如果有一個字節,readChar 將只返回一個字節。 您可以解決的方法如下:

  1. 檢查 stream 中是否有一些數據可用(可用應返回非空字節數)
  2. 用現有內容填充一個新的字節數組(后來轉換為字符串):用 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 example: 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());            
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM