【问题标题】:Convert file to byte array then to string then to byte array then to the original file将文件转换为字节数组,然后转换为字符串,然后转换为字节数组,然后转换为原始文件
【发布时间】:2017-04-14 20:25:57
【问题描述】:

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

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

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());
    }

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

【问题讨论】:

  • 任何帮助指出什么不起作用?你应该有每个功能的方法。这将更容易测试什么有效,什么无效。你应该从一个简单的文本文件开始......一个jpg更复杂,逐步检查值。
  • Java doc : String(byte[] bytes) Constructs a new String by **decoding** the specified array of bytes **using the platform's default charset**. 我认为这会修改您的内容
  • 将字节转换为字符串会破坏/更改它们。您可以在 C 中将字节存储在字符串中,但在 Java 中不能这样做。在 Java 中,您将字节存储在字节数组或ByteBuffer 中。这里根本不要使用字符串。
  • 您的意图是什么,您的用例是什么?试图将 JPEG 文件的字节解释为字符串没有任何意义。或者你的意思是你想要一个字节的字符串表示,比如 Base64,它用于通过文本协议传输二进制数据?
  • 是的,我想要一个字节的字符串表示形式,例如 Base64,它用于通过使用 htttp 但在 xml 节点中传输二进制数据

标签: java string file bitarray


【解决方案1】:

我找到了一个答案,必须使用 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());
    }

【讨论】:

    猜你喜欢
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2020-09-04
    • 2014-01-04
    相关资源
    最近更新 更多