文件转换为字节数组的三种方式。

本文介绍了三种将文件转换为字节数组的方法:传统IO、NIO和使用MappedByteBuffer的映射文件方式。通过对比,映射文件方式在处理大文件时能显著提升性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将文件转换为字节数组的io处理

文件转字节数组处理方式

  1. 传统io处理,应该比单纯nio还要快但是线程阻塞。
  2. nio处理方式,只是异步,并没有提高性能。
  3. 利用MappedByteBuffer 实现处理大文件提升性能。
package test;
import java.io.BufferedInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.RandomAccessFile;  
import java.nio.ByteBuffer;  
import java.nio.MappedByteBuffer;  
import java.nio.channels.FileChannel;  
import java.nio.channels.FileChannel.MapMode;  
 
 
public class FileUtils {  
 
   /** 
    * the traditional io way  
    * @param filename 
    * @return 
    * @throws IOException 
    */  
   public static byte[] toByteArray(String filename) throws IOException{  
         
       File f = new File(filename);  
       if(!f.exists()){  
           throw new FileNotFoundException(filename);  
       }  
       //此处出现问题当文件大于1.9G 数组装不下.
       ByteArrayOutputStream bos = new ByteArrayOutputStream((int)f.length());  
       BufferedInputStream in = null;  
       try{  
           in = new BufferedInputStream(new FileInputStream(f));  
           int buf_size = 1024;  
           byte[] buffer = new byte[buf_size];  
           int len = 0;  
           while(-1 != (len = in.read(buffer,0,buf_size))){  
               bos.write(buffer,0,len);  
           }  
           return bos.toByteArray();  
       }catch (IOException e) {  
           e.printStackTrace();  
           throw e;  
       }finally{  
           try{  
               in.close();  
           }catch (IOException e) {  
               e.printStackTrace();  
           }  
           bos.close();  
       }  
   }  
     
     
   /** 
    * NIO way 
    * @param filename 
    * @return 
    * @throws IOException 
    */  
   public static byte[] toByteArray2(String filename)throws IOException{  
         
       File f = new File(filename);  
       if(!f.exists()){  
           throw new FileNotFoundException(filename);  
       }  
         
       FileChannel channel = null;  
       FileInputStream fs = null;  
       try{  
           fs = new FileInputStream(f);  
           channel = fs.getChannel(); 
         //此处出现问题当文件大于1.9G 数组装不下.
           ByteBuffer byteBuffer = ByteBuffer.allocate((int)channel.size());  
           while((channel.read(byteBuffer)) > 0){  
               // do nothing  
//              System.out.println("reading");  
           }  
           return byteBuffer.array();  
       }catch (IOException e) {  
           e.printStackTrace();  
           throw e;  
       }finally{  
           try{  
               channel.close();  
           }catch (IOException e) {  
               e.printStackTrace();  
           }  
           try{  
               fs.close();  
           }catch (IOException e) {  
               e.printStackTrace();  
           }  
       }  
   }  
     
     
   /** 
    * Mapped File  way 
    * 可以在处理大文件时,提升性能 
    * @param filename 
    * @return 
    * @throws IOException 
    */  
   public static byte[] toByteArray3(String filename)throws IOException{  
         
       FileChannel fc = null;  
       try{  
           fc = new RandomAccessFile(filename,"r").getChannel();  
           MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();  
           System.out.println(byteBuffer.isLoaded()); 
         //此处出现问题当文件大于1.9G 数组装不下.
           byte[] result = new byte[(int)fc.size()];  
           if (byteBuffer.remaining() > 0) {  
//              System.out.println("remain");  
               byteBuffer.get(result, 0, byteBuffer.remaining());  
           }  
           return result;  
       }catch (IOException e) {  
           e.printStackTrace();  
           throw e;  
       }finally{  
           try{  
               fc.close();  
           }catch (IOException e) {  
               e.printStackTrace();  
           }  
       }  
   }  
}  
<think>我们正在处理用户的问题:如何通过文件的全路径将其内容读取为字节数组。 根据引用[1]和[2],我们知道Java的File类本身没有直接提供将文件转换字节数组的方法,但我们可以通过其他方式实现。 引用[1]提到了一些方法,包括使用Apache Commons、Google Guava或者Java标准库中的方法。 引用[2]则提醒我们在使用标准IO流时要注意读取和写入的字节数量,避免字节数组长度不正确。 我们可以提供几种方法: 1. 使用Java标准库(不使用第三方库) 2. 使用Apache Commons IO 3. 使用Google Guava 由于用户没有指定使用哪种方式,我们将提供多种方法,并说明注意事项。 注意:用户要求的是通过文件的全路径读取,所以我们需要使用文件路径字符串创建一个File对象或直接使用Paths工具。 另外,引用[3]中展示的是从URL读取图片并换为字节数组,但用户的需求是从本地文件路径读取,所以不适用。 下面我们分别给出几种实现方式:</think>### 如何将文件读取为字节数组 在Java中,可以通过以下方法将指定路径的文件读取为字节数组,确保正确处理文件流以避免内存泄漏和数组长度错误: #### 方法1:Java标准库(推荐) ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileToByteArray { public static byte[] readFile(String filePath) throws IOException { Path path = Paths.get(filePath); return Files.readAllBytes(path); // 自动处理文件关闭 } } ``` - **优点**:简洁安全,Java 7+ 原生支持,自动关闭资源 - **注意**:文件过大可能导致`OutOfMemoryError`,适用于中小文件 #### 方法2:FileInputStream + ByteArrayOutputStream(兼容旧版Java) ```java import java.io.*; public class FileToByteArray { public static byte[] readFile(String filePath) throws IOException { try (InputStream is = new FileInputStream(filePath); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); // 关键:按实际读取长度写入 } return baos.toByteArray(); } } } ``` - **关键点**: - 使用`try-with-resources`自动关闭流(Java 7+) - `len`确保只写入有效数据,避免数组长度错误[^2] - 缓冲区大小(1024)可根据文件大小调整 #### 方法3:Apache Commons IO(简化代码) ```java import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class FileToByteArray { public static byte[] readFile(String filePath) throws IOException { return FileUtils.readFileToByteArray(new File(filePath)); } } ``` - **依赖**:需添加`commons-io`库 - **优点**:单行实现,内部处理了所有异常和资源关闭 --- ### 注意事项 1. **大文件处理**:超过100MB的文件建议使用分块读取或内存映射(`MappedByteBuffer`) 2. **路径格式**: - Windows路径:`"C:\\dir\\file.txt"`(双反斜杠义) - Linux/Mac路径:`"/home/user/file.txt"` 3. **异常处理**: - 检查`FileNotFoundException` - 处理`SecurityException`(无文件访问权限) > 示例调用: > ```java > public static void main(String[] args) { > try { > byte[] data = readFile("D:/documents/report.pdf"); > System.out.println("读取字节数: " + data.length); > } catch (IOException e) { > e.printStackTrace(); > } > } > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值