【问题标题】:Convert file to byte array and vice versa将文件转换为字节数组,反之亦然
【发布时间】:2012-11-12 22:56:34
【问题描述】:

我找到了许多将文件转换为字节数组并将字节数组写入存储文件的方法。

我想要的是将java.io.File 转换为字节数组,然后将字节数组转换回java.io.File

我不想像下面这样将它写到存储中:

//convert array of bytes into file
FileOutputStream fileOuputStream = new FileOutputStream("C:\\testing2.txt"); 
fileOuputStream.write(bFile);
fileOuputStream.close();

我想以某种方式执行以下操作:

File myFile = ConvertfromByteArray(bytes);

【问题讨论】:

标签: java arrays


【解决方案1】:

否则试试这个:

将文件转换为字节

  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.IOException;


   public class Temp {

        public static void main(String[] args) {

         File file = new File("c:/EventItemBroker.java");

         byte[] b = new byte[(int) file.length()];
         try {
               FileInputStream fileInputStream = new FileInputStream(file);
               fileInputStream.read(b);
               for (int i = 0; i < b.length; i++) {
                           System.out.print((char)b[i]);
                }
          } catch (FileNotFoundException e) {
                      System.out.println("File Not Found.");
                      e.printStackTrace();
          }
          catch (IOException e1) {
                   System.out.println("Error Reading The File.");
                    e1.printStackTrace();
          }

       }
    }

将字节转换为文件

      public class WriteByteArrayToFile {

         public static void main(String[] args) {

            String strFilePath = "Your path";
            try {
                 FileOutputStream fos = new FileOutputStream(strFilePath);
                 String strContent = "Write File using Java ";

                 fos.write(strContent.getBytes());
                 fos.close();
           }
          catch(FileNotFoundException ex)   {
                 System.out.println("FileNotFoundException : " + ex);
          }
         catch(IOException ioe)  {
                 System.out.println("IOException : " + ioe);
          }

       }
     }

【讨论】:

  • 呃...OP说:“我不想把它写到存储”
  • 如何返回字节值?
【解决方案2】:

我认为您误解了 java.io.File 类的真正含义。它只是系统上文件的表示,即它的名称、它的路径等。

您甚至查看过java.io.File 类的Javadoc 吗?看看here 如果您检查它具有的字段或方法或构造函数参数,您会立即得到提示,它只是 URL/路径的表示。

Oracle 在其Java File I/O tutorial 中提供了相当广泛的教程,其中也包含最新的 NIO.2 功能。

使用 NIO.2,您可以使用 java.nio.file.Files.readAllBytes() 在一行中读取它。

同样,您可以使用java.nio.file.Files.write() 将所有字节写入字节数组中。

更新

由于问题被标记为 Android,更常规的方法是将 FileInputStream 包装在 BufferedInputStream 中,然后将其包装在 ByteArrayInputStream 中。 这将允许您阅读byte[] 中的内容。同样,它们的对应物存在于OutputStream

【讨论】:

  • 如果问题没有标记为 Android,这将是有用的信息。 java.nio.file 包不是 Android SDK(基于 Java 6)的一部分。
  • 你说得对,我没有注意到它被标记为 Android,我只阅读了标题和问题。我将添加Java 6方式。
【解决方案3】:

你不能这样做。 File 只是引用文件系统中文件的一种抽象方式。它本身不包含任何文件内容。

如果您尝试创建可以使用 File 对象引用的内存中文件,那么您也无法做到这一点,如 this thread、@987654322 中所述@ 和许多其他地方..

【讨论】:

    【解决方案4】:

    Apache FileUtil 提供了非常方便的方法来进行转换

    try {
        File file = new File(imagefilePath);
        byte[] byteArray = new byte[file.length()]();
        byteArray = FileUtils.readFileToByteArray(file);  
     }catch(Exception e){
         e.printStackTrace();
    
     }
    

    【讨论】:

    • 我们可以直接将文件作为参数传递给 readFileToByteArray(-) ,不需要用 "byte[] byteArray = new byte[file.length()](); 来初始化它,反正很有用建议..谢谢
    【解决方案5】:

    没有这样的功能,但你可以使用File.createTempFile()的临时文件。

    File temp = File.createTempFile(prefix, suffix);
    // tell system to delete it when vm terminates.
    temp.deleteOnExit();
    

    【讨论】:

    • 在 Android 上,您应该使用 Context.getCacheDir 获取临时文件目录并使用 3-arg 版本的 File.createTempFile()。这样,如果您忘记删除该文件,至少当您的应用数据被清除或您的应用被卸载时,它会消失。
    【解决方案6】:

    您不能对 File 执行此操作,它主要是一个智能文件路径。你能重构你的代码,让它声明变量,并传递参数,类型为OutputStream而不是FileOutputStream吗?如果是这样,请参阅课程 java.io.ByteArrayOutputStreamjava.io.ByteArrayInputStream

    OutputStream outStream = new ByteArrayOutputStream();
    outStream.write(whatever);
    outStream.close();
    byte[] data = outStream.toByteArray();
    InputStream inStream = new ByteArrayInputStream(data);
    ...
    

    【讨论】:

      【解决方案7】:

      1- 传统方式

      传统的转换方式是使用InputStream的read()方法,如下:

      public static byte[] convertUsingTraditionalWay(File file)
      {
          byte[] fileBytes = new byte[(int) file.length()]; 
          try(FileInputStream inputStream = new FileInputStream(file))
          {
              inputStream.read(fileBytes);
          }
          catch (Exception ex) 
          {
              ex.printStackTrace();
          }
          return fileBytes;
      }
      

      2-Java NIO

      在 Java 7 中,您可以使用 nio 包的 Files 实用程序类进行转换:

      public static byte[] convertUsingJavaNIO(File file)
      {
          byte[] fileBytes = null;
          try
          {
              fileBytes = Files.readAllBytes(file.toPath());
          }
          catch (Exception ex) 
          {
              ex.printStackTrace();
          }
          return fileBytes;
      }
      

      3- Apache Commons IO

      除了 JDK,您还可以通过 2 种方式使用 Apache Commons IO 库进行转换:

      3.1。 IOUtils.toByteArray()

      public static byte[] convertUsingIOUtils(File file)
      {
          byte[] fileBytes = null;
          try(FileInputStream inputStream = new FileInputStream(file))
          {
              fileBytes = IOUtils.toByteArray(inputStream);
          }
          catch (Exception ex) 
          {
              ex.printStackTrace();
          }
          return fileBytes;
      }
      

      3.2。 FileUtils.readFileToByteArray()

      public static byte[] convertUsingFileUtils(File file)
      {
          byte[] fileBytes = null;
          try
          {
              fileBytes = FileUtils.readFileToByteArray(file);
          }
          catch(Exception ex)
          {
              ex.printStackTrace();
          }
          return fileBytes;
      }
      

      【讨论】:

        【解决方案8】:

        服务器端

        @RequestMapping("/download")
        public byte[] download() throws Exception {
            File f = new File("C:\\WorkSpace\\Text\\myDoc.txt");
             byte[] byteArray = new byte[(int) f.length()];
                byteArray = FileUtils.readFileToByteArray(f);
                return byteArray;
        }
        

        客户端

        private ResponseEntity<byte[]> getDownload(){
            URI end = URI.create(your url which server has exposed i.e. bla 
                      bla/download);
            return rest.getForEntity(end,byte[].class);
        
        }
        
        public static void main(String[] args) throws Exception {
        
        
            byte[] byteArray = new TestClient().getDownload().getBody();
            FileOutputStream fos = new 
            FileOutputStream("C:\\WorkSpace\\testClient\\abc.txt");
        
             fos.write(byteArray);
             fos.close(); 
             System.out.println("file written successfully..");
        
        
        }
        

        【讨论】:

          【解决方案9】:
          //The file that you wanna convert into byte[]
          File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4"); 
          
          FileInputStream fileInputStream=new FileInputStream(file);
          byte[] data=new byte[(int) file.length()];
          BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
          bufferedInputStream.read(data,0,data.length);
          
          //Now the bytes of the file are contain in the "byte[] data"
          /*If you want to convert these bytes into a file, you have to write these bytes to a 
          certain location, then it will make a new file at that location if same named file is 
          not available at that location*/
          FileOutputStream fileOutputStream =new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/Video.mp4");
          fileOutputStream.write(data);
           /* It will write or make a new file named Video.mp4 in the "Download" directory of 
              the External Storage */
          

          【讨论】:

            猜你喜欢
            • 2015-02-16
            • 2013-11-11
            • 2013-03-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多