Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.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 读取时损坏的文件文本_Java_Io_Buffer_Inputstream - Fatal编程技术网

Java 读取时损坏的文件文本

Java 读取时损坏的文件文本,java,io,buffer,inputstream,Java,Io,Buffer,Inputstream,我有以下代码: 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

我有以下代码:

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();
        }
}

当我打印全文时,我看到较大文件的结尾部分再次添加到全文中。所以全文最后有几行重复。关于这里的错误有什么建议吗?

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

解决这个问题的一个方法可能是先将数据写入字符串,然后将字符串写入输出流。这也应该比每次读取后添加到字符串要快

将inputStream保存为字符串:

java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
fullText = s.hasNext() ? s.next() : "";
将字符串写入输出流:

out.write(fullText.getBytes());
如果希望保持代码的原样,则在缓冲区上执行子字符串,并仅检索读取的字节数。例如:

String line = (new String(buffer.substring(0,bytesRead));

<代码>新的字符串(缓冲器)使用整个缓冲器。您需要提供更多的参数来限制它使用的缓冲区的多少。顺便说一下,如果一个代码> >读取/代码>调用在多字节字符的中间结束,这将不起作用。抱歉,如果我不知道正确的缓冲区大小,会有什么问题。