2

我编写了这个程序来将一个 pdf 文件复制到另一个文件,但是我在 .txt 文件的 o/p 中得到了 currupt 字段,这段代码工作正常。

代码:

public class FileCopy {

    public static void main(String args[]) {

        try {
            FileInputStream fs = new FileInputStream("C:\\dev1.pdf");
            byte b;
            FileOutputStream os = new FileOutputStream("C:\\dev2.pdf");
            while ((b = (byte) fs.read()) != -1) {
                os.write(b);
            }
            os.close();
            fs.close();
        } catch (Exception E) {
            E.printStackTrace();
        }
    }
}
4

2 回答 2

4

这是因为您正在混合整数和字节。这应该按预期工作:

int b;
while ((b = fs.read()) != -1) {
    os.write(b);
}

特别是,当fs.read()返回 255 时,(byte) fs.read返回 -1。

于 2012-12-18T13:10:38.657 回答
3

试试这个

try {          
   FileInputStream fs = new FileInputStream("C:\\dev1.pdf");

   FileOutputStream os = new FileOutputStream("C:\\dev2.pdf");
   while ((int b = (byte) fs.read()) != -1) {
       os.write(b);
   }
   os.close();
   fs.close();
} catch (Exception E) {
    E.printStackTrace();
}
于 2012-12-18T13:25:30.327 回答