读取BufferedInputStream直到结束但“丢弃?”数据

时间:2014-01-19 09:12:28

标签: java io inputstream

我有一个我想调试的BufferedInputStream。出于这个目的,我使用这种方法(Log.d和Log.wtf只是特定于Android的日志工具,除此之外,行为不应该与纯Java不同):

    public static final String toString(BufferedInputStream is) {
    String ret = "";
    int readBytes = 0;

    is.mark(Integer.MAX_VALUE);

    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = null;
            try {
                reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
            }
            catch (UnsupportedEncodingException e) {
                Log.wtf("NX4", "Should never happen!", e);
            }
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
                readBytes += n;
            }
        }
        catch (IOException e) {
            Log.wtf("NX4", "Should never happen!", e);
        }
        finally {
            try {
                is.reset();
            }
            catch (IOException e) {
                Log.wtf("NX4", "Should never happen!", e);
            }
        }
        ret = writer.toString();
    }

    Log.d("NX4", "Read bytes: " + readBytes);

    return ret;
}

当我以this online XML file against which I'm testing right now运行时,同时我手动将文件下载到我的桌​​面,以便比较上述方法的输出和原始文件,我发生了一些事情根本不明白:

  1. 该方法正确读取5664个字节(来自Log.d(...)调用的信息)。
  2. 原始文件有5664个字符,这与第一个事实有关。
  3. 上述方法的输出长度仅为4254个字符!
  4. 我认为这可能与奇怪的间距问题有关,我不知道为什么会发生这种问题,而且不用说我不知道​​如何停止:

    Comparison of the original file and the output of the method

    编辑添加了BufferedInputStream创建代码段。

        URL source = new URL(srcString);
        URLConnection urlConnection = source.openConnection();
        urlConnection.connect();
        in = new BufferedInputStream(urlConnection.getInputStream());
    

1 个答案:

答案 0 :(得分:1)

可能坏内容是来自任何控制台的复制和粘贴结果。 检查一下:URLConnection cannot retrive complete Html