Java - 使用 InputStream 读取行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34954630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:10:33  来源:igfitidea点击:

Java - Read line using InputStream

javainputstream

提问by Ahmad Naoum

I use InputStream to read some data, so I want to read characters until new line or '\n'.

我使用 InputStream 读取一些数据,所以我想读取字符直到换行或 '\n'。

采纳答案by Tommaso Pasini

You should use BufferedReaderwith FileInputStreamReaderif your read from a file

如果您从文件中读取,您应该使用BufferedReaderwithFileInputStreamReader

BufferedReader reader = new BufferedReader(new FileInputStreamReader(pathToFile));

or with InputStreamReaderif you read from any other InputStream

或者InputStreamReader如果你从任何其他人那里读到InputStream

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

Then use its readLine() method in a loop

然后在循环中使用它的 readLine() 方法

while(reader.ready()) {
     String line = reader.readLine();
}

But if you really love InputStream then you can use a loop like this

但是如果你真的喜欢 InputStream 那么你可以使用这样的循环

InputStream stream; 
char c; 
String s = ""; 
do {
   c = stream.read(); 
   if (c == '\n')
      break; 
   s += c + "";
} while (c != -1);

回答by Rana

For files, the following will let you read each line:

对于文件,以下内容将让您阅读每一行:

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;

public static void readText throws FileNotFoundException(){

     Scanner scan = new Scanner(new File("filename.txt"));

     while(scan.hasNextLine()){
         String line = scan.nextLine();

     }
}

回答by Memin

It is possible to read input stream with BufferedReader and with Scanner. If you don't have a good reason,it is better to use BufferedRead (for broad discussion BufferedReader vs Scanner see.

可以使用 BufferedReader 和 Scanner 读取输入流。如果没有充分的理由,最好使用 BufferedRead(有关 BufferedReader 与 Scanner 的广泛讨论,请参阅.

I would also suggest using the Buffered Reader with try-with-resources to make sure the resource are auto-closed. see

我还建议将 Buffered Reader 与 try-with-resources 一起使用,以确保资源自动关闭。

See the following code

看下面的代码

try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
        while (reader.ready()) {
            String line = reader.readLine();
            System.out.println(line);
        }
    }catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }