这是我的代码,imageFile
是一个pdf
文件,目的是获取Base64
图像文件的编码文件。我正在使用Java6
并且不可能升级到Java7
Base64Inputstream
是类型org.apache.commons.codec.binary.Base64InputStream
private File toBase64(File imageFile) throws Exception {
LOG.info(this.getClass().getName() + " toBase64 method is called");
System. out.println("toBase64 is called" );
Base64InputStream in = new Base64InputStream(new FileInputStream(imageFile), true );
File f = new File("/root/temp/" + imageFile.getName().replaceFirst("[.][^.]+$" , "" ) + "_base64.txt" );
Writer out = new FileWriter(f);
copy(in, out);
return f;
}
private void copy(InputStream input, Writer output)
throws IOException {
InputStreamReader in = new InputStreamReader(input);
copy(in, output);
}
private int copy(Reader input, Writer output) throws IOException {
long count = copyLarge(input, output);
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int) count;
}
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private long copyLarge(Reader input, Writer output) {
char[] buffer = new char[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
try {
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
System.out.println("Count: " + count);
}
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
我正在使用IOUtils.copy(InputStream input, Writer output)
方法。但是对于某些pdf
文件(注意,不是全部)它会抛出异常。因此,在调试过程中,我IOUtils.copy
在本地复制了代码,并在Count: 2630388
. 这是堆栈跟踪:
Root Exception stack trace:
java.io.IOException: Underlying input stream returned zero bytes
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:268)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
上面所说的这个块在什么情况下会抛出异常:
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
System.out.println("Count: " + count);
}
请帮助我了解原因以及如何解决