阅读时损坏的文件文本

问题描述 投票:-1回答:1

我有以下代码:

BlobDomain blobDomain = null;
OutputStream out = null;
try {
    blobDomain = new BlobDomain();
    out = blobDomain.getBinaryOutputStream();
    byte[] buffer = new byte[8192];
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
        out.write(buffer, 0, bytesRead);
        String line = (new String(buffer));
        fullText += line;
    }

} catch (Exception e) {
    //do nothing
}finally{            
    if (out != null)
        try {
            out.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
}

当我打印fullText时,我看到的更大的文件是文本的结尾部分再次添加到fullText。所以全文最后会重复一些。关于这里有什么问题的任何建议?

java io buffer inputstream
1个回答
1
投票

你得到这个的原因是你每次都在写你的字符串整个缓冲区。因此,当您到达文件末尾时,您可能没有准确读取缓冲区大小的字节数。旧数据仍在缓冲区中,也将写入String。

解决此问题的一个选择可能是首先将数据写入String,然后将String写入输出流。这也应该比每次读取后添加到String更快。

将inputStream保存到String:

java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
fullText = s.hasNext() ? s.next() : "";

将String写入输出流:

out.write(fullText.getBytes());

如果要保持代码原样,则在缓冲区上执行子字符串,并仅检索读取的字节数。例如:

String line = (new String(buffer.substring(0,bytesRead));
© www.soinside.com 2019 - 2024. All rights reserved.