-1

下面是我将 PDF 文件转换为字节数组的代码

public class ByteArrayExample{
public static void main(String[] args) {
    try{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter File name: ");
        String str = bf.readLine();
        File file = new File(str); 
        //File length
        int size = (int)file.length(); 
        if (size > Integer.MAX_VALUE){
            System.out.println("File is to larger");
        }
        byte[] bytes = new byte[size]; 
        DataInputStream dis = new DataInputStream(new FileInputStream(file)); 
        int read = 0;
        int numRead = 0;
        while (read < bytes.length && (numRead=dis.read(bytes, read,
                bytes.length-read)) >= 0) {
            read = read + numRead;
        }
        System.out.println("File size: " + read);
        // Ensure all the bytes have been read in
        if (read < bytes.length) {
            System.out.println("Could not completely read: "+file.getName());
        }
    }
  catch (Exception e){
  e.getMessage();
  }
  }
}

问题是这实际上将文件名转换为字节数组而不是实际的 PDF 文件。任何人都可以帮我解决这个问题。

4

1 回答 1

1

我将其添加到最后以检查它并复制了 PDF 文件。你的代码工作正常

        dis.close();

        DataOutputStream out = new DataOutputStream(new FileOutputStream(new File("c:\\out.pdf")));
        out.write(bytes);
        out.close();
        System.out.println("File size: " + read);
        // Ensure all the bytes have been read in
        if (read < bytes.length) {
            System.out.println("Could not completely read: "+file.getName());
        }

编辑:这是我的整个代码,它只是从你的代码中复制而来的。我在 IDE (eclipse) 中运行它并输入“c:\mypdf.pdf”作为输入,并将其复制到 out.pdf。相同的副本。请注意,我确实关闭了我注意到您在代码中忘记执行的两个流。

public class Main {

public static void main(String[] args) {
    try {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter File name: ");
        String str = bf.readLine();
        File file = new File(str);
        //File length
        int size = (int) file.length();
        if (size > Integer.MAX_VALUE) {
            System.out.println("File is to larger");
        }
        byte[] bytes = new byte[size];
        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        int read = 0;
        int numRead = 0;
        while (read < bytes.length && (numRead = dis.read(bytes, read,
                bytes.length - read)) >= 0) {
            read = read + numRead;
        }
        dis.close();

        DataOutputStream out = new DataOutputStream(new FileOutputStream(new File("c:\\out.pdf")));
        out.write(bytes);
        out.close();
        System.out.println("File size: " + read);

        // Ensure all the bytes have been read in
        if (read < bytes.length) {
            System.out.println("Could not completely read: " + file.getName());
        }
    } catch (Exception e) {
        e.getMessage();
    }
}

}

于 2013-04-30T17:35:50.430 回答