【问题标题】:byte[] to file in Javabyte[] 到 Java 中的文件
【发布时间】:2011-05-20 00:03:56
【问题描述】:

使用 Java:

我有一个代表文件的byte[]

如何将其写入文件(即C:\myfile.pdf

我知道它已经用 InputStream 完成了,但我似乎无法解决它。

【问题讨论】:

    标签: java arrays file io inputstream


    【解决方案1】:

    使用Apache Commons IO

    FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
    

    或者,如果你坚持为自己工作......

    try (FileOutputStream fos = new FileOutputStream("pathname")) {
       fos.write(myByteArray);
       //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
    }
    

    【讨论】:

    • @R. Bemrose 好吧,它可能设法在可悲的情况下清理资源。
    • 来自文档:注意:从 v1.3 开始,如果文件的父目录不存在,则将创建它们。
    • 如果写入失败,会泄漏输出流。您应该始终使用try {} finally {} 来确保正确清理资源。
    • fos.close() 语句是多余的,因为您正在使用 try-with-resources 自动关闭流,即使写入失败。
    • 为什么我会使用 apache commons IO,因为它是 2 行普通 Java
    【解决方案2】:

    没有任何库:

    try (FileOutputStream stream = new FileOutputStream(path)) {
        stream.write(bytes);
    }
    

    Google Guava:

    Files.write(bytes, new File(path));
    

    Apache Commons:

    FileUtils.writeByteArrayToFile(new File(path), bytes);
    

    所有这些策略都要求您在某个时候也捕获 IOException。

    【讨论】:

    • 这种情况下 charset 怎么样?
    • @pavan 字符集 path? FileOutputStream 文档没有提到这一点,因此这可能是特定于平台的。我猜在大多数情况下它是 UTF-8。 bytes 按原样编写,不涉及字符集。
    【解决方案3】:

    使用java.nio.file的另一种解决方案:

    byte[] bytes = ...;
    Path path = Paths.get("C:\\myfile.pdf");
    Files.write(path, bytes);
    

    【讨论】:

    • 我不认为 C:\myfile.pdf 无论如何都可以在 Android 上运行... ;)
    • @TB 在这种情况下 charset 怎么样?
    • charset 似乎无关紧要,因为我们写的是字节,而不是字符
    • 你说的是真的,我理解我的错误。
    【解决方案4】:

    同样从 Java 7 开始,一行 java.nio.file.Files:

    Files.write(new File(filePath).toPath(), data);
    

    其中 data 是你的 byte[] 并且 filePath 是一个字符串。您还可以使用 StandardOpenOptions 类添加多个文件打开选项。使用 try/catch 添加 throws 或环绕。

    【讨论】:

    • 你可以用Paths.get(filePath);代替new File(filePath).toPath()
    • @Halil 我认为这不对。根据 javadocs,打开选项有一个可选的第三个参数,“如果不存在任何选项,则此方法就像存在 CREATE、TRUNCATE_EXISTING 和 WRITE 选项一样工作。换句话说,它打开文件进行写入,创建如果文件不存在,或者最初将现有的常规文件截断为 0 的大小。"
    【解决方案5】:

    Java 7 开始,您可以使用 try-with-resources 语句来避免资源泄漏并使代码更易于阅读。更多关于 here.

    要将您的byteArray 写入您可以执行的文件:

    try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
        fos.write(byteArray);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    

    【讨论】:

    • 我尝试使用它,但它会导致非 UTF-8 字符的字节出现问题,因此如果您尝试编写单个字节来构建文件,我会小心处理这个问题,因为例子。
    【解决方案6】:

    试试OutputStream 或更具体的FileOutputStream

    【讨论】:

      【解决方案7】:

      基本示例:

      String fileName = "file.test";
      
      BufferedOutputStream bs = null;
      
      try {
      
          FileOutputStream fs = new FileOutputStream(new File(fileName));
          bs = new BufferedOutputStream(fs);
          bs.write(byte_array);
          bs.close();
          bs = null;
      
      } catch (Exception e) {
          e.printStackTrace()
      }
      
      if (bs != null) try { bs.close(); } catch (Exception e) {}
      

      【讨论】:

        【解决方案8】:
        File f = new File(fileName);    
        byte[] fileContent = msg.getByteSequenceContent();    
        
        Path path = Paths.get(f.getAbsolutePath());
        try {
            Files.write(path, fileContent);
        } catch (IOException ex) {
            Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
        }
        

        【讨论】:

          【解决方案9】:

          ////////////////////// 1] 文件到字节[] ///////////// /////

          Path path = Paths.get(p);
                              byte[] data = null;                         
                              try {
                                  data = Files.readAllBytes(path);
                              } catch (IOException ex) {
                                  Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
                              }
          

          /////////////////// 2]字节[]到文件////////////// //////////

           File f = new File(fileName);
           byte[] fileContent = msg.getByteSequenceContent();
          Path path = Paths.get(f.getAbsolutePath());
                                      try {
                                          Files.write(path, fileContent);
                                      } catch (IOException ex) {
                                          Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
                                      }
          

          【讨论】:

          • 感谢您的回答..但我对“文件名”感到困惑,我的意思是您保存数据的文件类型是什么?你能解释一下吗?
          • 您好 SRam,这完全取决于您的应用程序为什么要进行转换以及您想要输出的格式,我建议使用 .txt 格式(例如:-myconvertedfilename.txt)但又是你的选择。
          【解决方案10】:

          我知道它是用 InputStream 完成的

          实际上,您应该是 writingfile output...

          【讨论】:

            【解决方案11】:

            这是一个程序,我们使用 String Builder 读取和打印字节偏移和长度数组,并将字节偏移长度数组写入新文件。

            `在此处输入代码

            import java.io.File;   
            import java.io.FileInputStream;
            import java.io.FileOutputStream;
            import java.io.IOException;        
            
            //*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//     
            
            public class ReadandWriteAByte {
                public void readandWriteBytesToFile(){
                    File file = new File("count.char"); //(abcdefghijk)
                    File bfile = new File("bytefile.txt");//(New File)
                    byte[] b;
                    FileInputStream fis = null;              
                    FileOutputStream fos = null;          
            
                    try{               
                        fis = new FileInputStream (file);           
                        fos = new FileOutputStream (bfile);             
                        b = new byte [1024];              
                        int i;              
                        StringBuilder sb = new StringBuilder();
            
                        while ((i = fis.read(b))!=-1){                  
                            sb.append(new String(b,5,5));               
                            fos.write(b, 2, 5);               
                        }               
            
                        System.out.println(sb.toString());               
                    }catch (IOException e) {                    
                        e.printStackTrace();                
                    }finally {               
                        try {              
                            if(fis != null);           
                                fis.close();    //This helps to close the stream          
                        }catch (IOException e){           
                            e.printStackTrace();              
                        }            
                    }               
                }               
            
                public static void main (String args[]){              
                    ReadandWriteAByte rb = new ReadandWriteAByte();              
                    rb.readandWriteBytesToFile();              
                }                 
            }                
            

            控制台中的O/P:fghij

            新文件中的 O/P :cdefg

            【讨论】:

              【解决方案12】:

              你可以试试Cactoos:

              new LengthOf(new TeeInput(array, new File("a.txt"))).value();
              

              更多详情:http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html

              【讨论】:

                猜你喜欢
                • 2021-12-24
                • 1970-01-01
                • 2019-03-01
                • 1970-01-01
                • 2015-01-16
                • 1970-01-01
                • 1970-01-01
                • 2013-03-07
                相关资源
                最近更新 更多