File转byte数组,对比

本文对比了四种Java文件读取方式的性能:BIO、带有缓冲的BIO、NIO拼接数组方式以及NIO2。在读取7M大小文件的10次平均耗时中,BIO平均耗时223ms,BIO-Buffered为206ms,NIO2同样为214ms,而NIO-拼接数组方式耗时高达5467ms。性能问题主要出现在NIO的拼接数组方式,由于数据频繁复制移动导致效率降低。其他三种方式表现相近。

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

1、BIO方式

    /**
     * 将文件转换成byte数组
     * @param filePath
     * @return
     */
    public static byte[] File2byteBIO(File tradeFile){
        byte[] buffer = null;
        try(FileInputStream fis = new FileInputStream(tradeFile);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();){
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1){
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

2、BIO-Buffered

    public static byte[] File2byteBuffered(File tradeFile){
    	byte[] buffer = null;
    	try(FileInputStream fis = new FileInputStream(tradeFile);
        		ByteArrayOutputStream bos = new ByteArrayOutputStream();
        		BufferedOutputStream bb = new BufferedOutputStream(bos); ){
    		byte[] b = new byte[1024];
    		int n;
    		while ((n = fis.read(b)) != -1){
    			bb.write(b, 0, n);
    		}
    		fis.close();
    		bos.close();
    		buffer = bos.toByteArray();
    	}catch (FileNotFoundException e){
    		e.printStackTrace();
    	}catch (IOException e){
    		e.printStackTrace();
    	}
    	return buffer;
    }

3、NIO-拼接数组方式

    public static byte[] File2byteNIO(File tradeFile){
            byte[] retval = null;  
            try(FileInputStream fileInputStream = new FileInputStream(tradeFile);) {  
                FileChannel inChannel = fileInputStream.getChannel();  
                ByteBuffer buf = ByteBuffer.allocate(1024);  
                int byteRead = inChannel.read(buf);  
                int readLength = 0;  
                while (byteRead != -1){  
                    buf.flip();  
                    byte[] tempval = null;  
                    //以下代码划重点!!!!!!!!  
                    if (retval == null){  
                        retval = new byte[byteRead];  
                    }else{  
                        tempval = retval;  
                        readLength = tempval.length;  
                        retval = new byte[readLength+byteRead];  
                        System.arraycopy(tempval, 0, retval, 0, tempval.length);  
                    }  
                    int i = readLength;  
                    while (buf.hasRemaining()){  
                        byte b = buf.get();  
                        retval[i] = b;  
                        i++;  
                    }  
                    buf.clear();  
                    byteRead = inChannel.read(buf);  
                }  
                  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            return retval;  
    }

4、NIO2

    public static byte[] File2byteNIO2(File tradeFile){
    	byte[] retval = null;  
    	try(FileInputStream fileInputStream = new FileInputStream(tradeFile);) {  
    		FileChannel inChannel = fileInputStream.getChannel();  
    		ByteBuffer buf = ByteBuffer.allocateDirect((int)inChannel.size()); //文件太大的话这里必然报错 
    		inChannel.read(buf);  
    		retval = new byte[(int)inChannel.size()];
    		buf.get(retval, 0, buf.remaining());
    	} catch (FileNotFoundException e) {  
    		e.printStackTrace();  
    	} catch (IOException e) {  
    		e.printStackTrace();  
    	}  
    	return retval;  
    }

文件大小:7M 

方式   10次平均耗时
BIO平均:223ms
BIO-Buffered平均:206ms
NIO-拼接数组方式耗时:5467ms
NIO2平均:214ms

总结:拼接数组导致数据频繁的复制移动,影响性能,其他都差不多。

<think>好的,我需要解决用户的问题:如何使用Java的transferTo方法将byte数组保存为文件。首先,我得确认transferTo方法的来源。用户提到的引用中提到了InputStream和MultipartFile,可能涉及到Spring框架中的MultipartFile接口。 我记得在Spring的MultipartFile接口中有一个transferTo方法,它可以将上传的文件传输到目标文件中。所以用户可能是想将byte数组换为MultipartFile,然后调用transferTo方法保存为文件。但首先,如何从byte数组创建MultipartFile呢? 根据引用[3],用户提到可以将字节数组换为MultipartFile对象。通常,这需要创建一个MockMultipartFile实例,这是Spring提供的测试工具类。因此,步骤可能是:将byte数组包装成MultipartFile,然后调用transferTo方法。 不过,需要注意的是,transferTo方法属于MultipartFile,而不是直接处理byte数组。所以用户需要先将byte数组换为MultipartFile对象,这可能需要使用ByteArrayInputStream或者通过MockMultipartFile构造函数。 接下来,我需要确保示例代码的正确性。例如,创建MockMultipartFile时需要指定文件名、原始文件名、内容类型和字节数组。然后调用transferTo方法,传入目标文件路径。 另外,需要处理可能的异常,如IOException,并确保文件保存路径存在。如果用户直接有byte数组,不需要从上传获取,所以示例应展示如何从头创建MultipartFile。 还要检查是否需要添加Spring框架的相关依赖,比如spring-test和spring-web,以便使用MockMultipartFile类。但用户可能已经了解这些,所以示例中可能需要包含必要的import语句。 最后,生成相关问题时要考虑用户可能遇到的后续问题,比如异常处理、性能优化、与其他方法的比较等。确保问题覆盖用户可能感兴趣的方向。</think>### 如何通过 `transferTo` 方法将 byte 数组保存为文件? 在 Java 中,`transferTo` 是 `MultipartFile` 接口提供的方法,用于将上传的文件内容直接传输到目标文件[^3]。若要从 byte 数组创建文件,需先将 byte 数组换为 `MultipartFile` 对象,再调用 `transferTo` 方法。以下是完整示例: #### 步骤解析 1. **创建 MultipartFile 对象** 使用 Spring 提供的 `MockMultipartFile` 类(测试工具类)将 byte 数组包装为 `MultipartFile` 对象。 2. **调用 transferTo 方法** 将 `MultipartFile` 的内容保存到指定路径的文件中。 #### 示例代码 ```java import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class ByteToFileExample { public static void main(String[] args) { // 1. 定义 byte 数组和文件名 byte[] fileBytes = "Hello, World!".getBytes(); String fileName = "example.txt"; // 2. 创建 MultipartFile 对象 MultipartFile multipartFile = new MockMultipartFile( fileName, // 表单字段名 fileName, // 原始文件名 "text/plain", // 内容类型 fileBytes // byte 数组 ); // 3. 保存到文件 try { Path targetPath = Paths.get("path/to/save/" + fileName); multipartFile.transferTo(targetPath.toFile()); System.out.println("文件保存成功"); } catch (IOException e) { e.printStackTrace(); } } } ``` #### 关键说明 - **依赖要求**:需引入 Spring Web 模块(如 `spring-web`)和测试工具(如 `spring-test`)以使用 `MockMultipartFile`。 - **异常处理**:`transferTo` 可能抛出 `IOException`,需捕获处理。 - **路径有效性**:确保目标目录存在,否则会抛出 `FileNotFoundException`。 #### 其他方法对比 若无需使用 `transferTo`,可直接通过 `Files.write()` 保存 byte 数组: ```java Path path = Paths.get("path/to/file.txt"); Files.write(path, fileBytes); ``` 此方法更简洁,但 `transferTo` 适用于已存在 `MultipartFile` 的场景(如文件上传处理)。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值