有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA:使用InputStreamReader打开并读取文件

我正在尝试使用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文件


共 (2) 个答案

  1. # 1 楼答案

    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重复读取小字节数组(缓冲区)

  2. # 2 楼答案

    不要使用读写器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);