0

我正在尝试使用 InputStreamReader 读取二进制文件(pdf、doc、zip)。我使用 FileInputStream 实现了这一点,并将文件的内容保存到字节数组中。但是我被要求使用 InputStreamReader 来做到这一点。因此,当我尝试打开和阅读 pdf 文件时,例如使用

File file = new File (inputFileName); 
Reader in = new
InputStreamReader(new FileInputStream(file)); 
char fileContent[] = new char[(int)file.length()]; 
in.read(fileContent); in.close();

然后将此内容保存到另一个pdf文件使用

File outfile = new File(outputFile);
Writer out = new OutputStreamWriter(new FileOutputStream(outfile));
out.write(fileContent);
out.close();

一切正常(没有异常或错误),但是当我尝试打开新文件时,它要么说它已损坏,要么编码错误。

有什么建议吗??

ps1 我特别需要这个使用 InputStreamReader

ps2 在尝试读/写 .txt 文件时工作正常

4

2 回答 2

2

String, char, Reader, Writer用于java中的文本。此文本是 Unicode,因此可以组合所有脚本。

byte[], InputStream, OutputStream用于二进制数据。如果它们代表文本,它们必须与某种编码相关联。

文本和二进制数据之间的桥梁总是涉及转换。

在你的情况下:

Reader in = new InputStreamReader(new FileInputStream(file), encoding);
Reader in = new InputStreamReader(new FileInputStream(file)); // Platform's encoding

第二个版本是不可移植的,因为其他计算机可以有任何编码。

在您的情况下,请勿将 InputStreamReader 用于二进制数据。转换只能破坏事物。

也许他们的意思是:不要在字节数组中读取所有内容。在这种情况下,使用 BufferedInputStream 重复读取小字节数组(缓冲区)。

于 2014-10-09T14:30:44.790 回答
1

不要使用读取器/写入器 API。改用二进制流:

File inFile = new File("...");
File outFile = new File("...");
FileChannel in = new FileInputStream(inFile).getChannel();
FileChannel out = new FileOutputStream(outFile).getChannel();

in.transferTo(0, inFile.length(), out);
于 2014-10-09T14:30:26.437 回答