由于之前的实现需要使用InputStream
,因此我无法使用BufferedReader
。使用InputStream读取文件的一行
我的测试平台使用的BufferedReader
和while循环,就像这样:
while ((line = br.readLine()) != null)
但是BR现在需要是一个InputStream
(将改名)。有没有什么方法可以用InputStream
这种方式阅读,或者我必须一次读取它的字节数并搜索\n
?
由于之前的实现需要使用InputStream
,因此我无法使用BufferedReader
。使用InputStream读取文件的一行
我的测试平台使用的BufferedReader
和while循环,就像这样:
while ((line = br.readLine()) != null)
但是BR现在需要是一个InputStream
(将改名)。有没有什么方法可以用InputStream
这种方式阅读,或者我必须一次读取它的字节数并搜索\n
?
如果您必须使用InputStream进行读取,然后将其包装到InputStreamReader中,然后将其包装到BufferedReader中,以便使用您熟悉的BufferedReader方法。在这种情况下,不需要做非缓冲输入。
// assuming that you have an InputStream named inputStream
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while((line = br.readLine()) != null) {
// use line here
}
} catch (IOException e) {
e.printStackTrace();
}
或者,包裹的InputStream在扫描对象:
try (Scanner scanner = new Scanner(inputStream)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// use line here
}
}
你可以改变这样代码:
public String readLine(InputStream inputStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r;
for (r = inputStream.read(); r != '\n' && r != -1 ; r = inputStream.read()) {
baos.write(r);
}
if (r == -1 && baos.size() == 0) {
return null;
}
String lines = baos.toString("UTF-8");
return lines;
}
也许这个例子可以帮助你..
可能的重复o f http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string –