java - 将文件转换为字节数组,反之亦然

标签 java arrays

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

我想要的是将 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);

最佳答案

否则试试这个:

将文件转换为字节

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

       }
     }

关于java - 将文件转换为字节数组,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352972/

相关文章:

java - 重载方法如何工作?

c++ - 我是否应该始终声明比我的字符串大的 char 数组?

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 异常?我该如何预防?

c - 如何仅在C中接受字符输入?

Java - 正则表达式解析x匹配的出现

javafx 在 Netbeans IDE 之外运行应用程序

Java 可调整大小的位数组?

java - 使用 jar 作为资源存档的简单方法

C++ 将字符串(带空格)显示为二维数组?

c - SIMD 数组添加任意数组长度