'Java - Read line using InputStream [duplicate]
I use InputStream to read some data, so I want to read characters until new line or '\n'.
Solution 1:[1]
TL;DR
Use BufferedReader within the try-with block, which will close the resource after finishing with it.
It is possible to read the 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).
I would also suggest using the Buffered Reader with try-with-resources to make sure the resource are auto-closed. see
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();
}
Solution 2:[2]
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();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rana |
