Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 来自一个InputStream的2个BufferedReader_Java_Url - Fatal编程技术网

Java 来自一个InputStream的2个BufferedReader

Java 来自一个InputStream的2个BufferedReader,java,url,Java,Url,我编写了以下代码: try { URL url = new URL("http://bbc.com"); is = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); System.out.println(in.readLine()); //in.close(); with this next lines throw java.io.IOEx

我编写了以下代码:

try {
  URL url = new URL("http://bbc.com");
  is = url.openStream();
  BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  System.out.println(in.readLine());
  //in.close(); with this next lines throw java.io.IOException: stream is closed
  in = new BufferedReader(new InputStreamReader(is, "iso-8859-2"));
  System.out.println(in.readLine().length());
} catch (Exception ex) {
  ex.printStackTrace();
}

问题在于,几乎每次程序运行后,第二个BufferedReader都会从几个不同的点开始读取(打印长度不同)。同样的编码也会出现同样的问题。如何读取编码,然后使用此编码读取内容而不创建新的InputStream(每次创建新InputStream都需要0.1到3秒,具体取决于站点)?

我建议您复制整个流,例如重复调用
read()
,然后将结果写入
ByTearrayOutstream
。然后可以从中获取字节数组,并围绕字节数组创建多个独立的
ByteArrayInputStream
包装器

(您可以使用Guava的
ByTestStreams.ToByteArray(is)
作为第一部分的替代。)


另一种选择是将原始的
InputStream
封装在
BufferedInputStream
中,立即调用
mark
,并设置一个“足够大”的限制,然后在读取第一行后重置它,然后再创建第二行
BufferedReader

我不会使用BufferedReader读取第一行,我只需读取字符,直到在代码中将.readLine()改为.read()中的(char)时找到一个“\n”。

第二个打印字符几乎在每个程序运行时都是不同的。当然,只要您知道第一行的长度是合理的。如果没有这个保证,您应该手动为第一行执行缓冲。@Andrej是的,问题是BufferedReader将尝试填充其缓冲区(调用read()时的事件)。这就是为什么你不应该使用它。