将文件转换为字节数组然后转换为字符串然后转换为字节数组然后转换为原始文件

时间:2016-11-30 13:27:55

标签: java string file bitarray

我尝试(在Java中)获取文件文档,然后将其转换为bitArray,然后转换为类似表示的String,然后返回到原始位数组,最后转换为原始最终文档。

这是我的代码,但生成的文件在这种情况下无法查看图像。

try {
        File file = new File("C:/Users/dkimigho/Downloads/kenyapowerlogo.jpg");

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //create FileInputStream which obtains input bytes from a file in a file system
        //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                //Writes to this byte array output stream
                bos.write(buf, 0, readNum); 
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(ARRAYBITStoPDF.class.getName()).log(Level.SEVERE, null, ex);
        }

        byte[] bytes = bos.toByteArray();

        System.out.println("byte1");
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i]);
        }
        //We have the bytes now convert to String
        String stringbytearray=new String(bytes);

        System.out.println("stringbytearray: "+stringbytearray);

        //We have the bytes now convert to String

        byte[] content = stringbytearray.getBytes();
        System.out.println("byte2");
        for (int i = 0; i < content.length; i++) {
            System.out.print(content[i]);
        }

        int size = bytes.length;
        InputStream isfilecontent = null;
        byte[] b = new byte[size];
        isfilecontent = new ByteArrayInputStream(content);

        //writing the downloaded data into a PDF file
         FileOutputStream fileOutputpdf = new FileOutputStream("C:/Users/dkimigho/Downloads/mykenyapowerlogo.jpg");

         /* use binary I/O to prevent line based operation messing with the encoding.*/
         byte[] buf2 = new byte[2048];
         int b_read = 0;
         while ( (b_read = isfilecontent.read(buf2)) > 0) {
             fileOutputpdf.write(buf2, 0, b_read);
         }
         fileOutputpdf.flush();
         //closed the output stream
         fileOutputpdf.close();

     } catch (IOException e) {
        // handle IOException
         System.out.println(e.getMessage());
    }

指出我做错了什么的任何帮助?将我的代码更正为工作代码可能很重要。

1 个答案:

答案 0 :(得分:0)

我找到了一个答案,必须使用JAVA 8 java.util.Base64对字节进行编码和解码,而不会丢失文档上的信息。我希望这会对某人有所帮助。

/*
     * 1. How to convert an image file to  byte array?
     */
    try {
        File file = new File("C:/Users/qwerty/Downloads/factura.pdf");

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //create FileInputStream which obtains input bytes from a file in a file system
        //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                //Writes to this byte array output stream
                bos.write(buf, 0, readNum); 
               // System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(ARRAYBITStoPDF.class.getName()).log(Level.SEVERE, null, ex);
        }

        byte[] bytes = bos.toByteArray();
        bos.close(); // should be inside a finally block
        //We have the bytes now convert to String

        // ENCODING
        String encodedDoc= Base64.getEncoder().encodeToString(bytes);

        System.out.println(encodedDoc);

        // DECODING
        int size = bytes.length;
        InputStream isfilecontent = null;
        //byte[] b = new byte[size];
        isfilecontent = new ByteArrayInputStream(Base64.getDecoder().decode(encodedDoc));

        //writing the downloaded data into a PDF file
         FileOutputStream fileOutputpdf = new FileOutputStream("C:/Users/qwerty/Downloads/myfactura.pdf");

         /* use binary I/O to prevent line based operation messing with the encoding.*/
         byte[] buf2 = new byte[2048];
         int b_read = 0;
         while ( (b_read = isfilecontent.read(buf2)) > 0) {
             fileOutputpdf.write(buf2, 0, b_read);
         }
         fileOutputpdf.flush();
         //closed the output stream
         fileOutputpdf.close();

     } catch (IOException e) {
        // handle IOException
         System.out.println(e.getMessage());
    }