Java 读写byte[]类

本文详细介绍了使用Java进行文件操作的多种方法,包括如何读取文件内容为字节数组,以及如何将字节数组写入文件。通过示例代码,展示了不同场景下文件读写的实现方式,如直接读取、流操作以及追加写入等。
package tools;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class FileHelper {
    //第一种获取文件内容方式
    public byte[] readByte(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "+ file.getName());
        }
        fi.close();
        return buffer;
    }

    //第二种获取文件内容方式
    public byte[] readByte2(String filePath) throws IOException
    {
        FileInputStream in=new FileInputStream(filePath);
        ByteArrayOutputStream out=new ByteArrayOutputStream(1024);
        System.out.println("bytes available:"+in.available());
        byte[] temp=new byte[1024];
        int size=0;
        while((size=in.read(temp))!=-1)
        {
            out.write(temp,0,size);
        }
        in.close();
        byte[] bytes=out.toByteArray();
        System.out.println("bytes size got is:"+bytes.length);
        return bytes;
    }
    //将byte数组写入文件
    public void WriteByteToFile(String path, byte[] content) throws IOException {
        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }
    /* 方法1:
     * 将byte数组(追加)写入文件
     *
     * */
    public void AppendByteToFile(String path, byte[] content, boolean Appendable) throws IOException {
//         程序写好之后每次存储数据都刷新
        //FileOutputStream fos = new FileOutputStream(path);
//         研究了一下,原来FileOutPutStream也可以设置模式的,只是和openFileOutput不一样 我这样写FileOutputStream fos=new FileOutputStream(_sdpath1,Appendable);就可以实现数据追加功能
        FileOutputStream fos=new FileOutputStream(path,Appendable);
        fos.write(content);
        fos.write("\r\n".getBytes());
        fos.close();
    }
    /**
     * 方法二:
     * 根据byte数组,生成文件
     */
    public  void AppendByteToFile(byte[] bfile, String filePath,String fileName) {
        BufferedOutputStream bos = null;

        File file = null;
        try {
            File dir = new File(filePath);
            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath+"\\"+fileName);
            /* 使用以下2行代码时,不追加方式*/
            /*bos = new BufferedOutputStream(new FileOutputStream(file));
            bos.write(bfile); */
            /* 使用以下3行代码时,追加方式*/
            bos = new BufferedOutputStream(new FileOutputStream(file, true));
            bos.write(bfile);
            bos.write("\r\n".getBytes());

            bos.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

        }
    }
}

<think>嗯,用户现在想找Java中使用Byte进行文件读写的API和方法,还要求示例。我需要先理清楚Java中处理字节流的相关。 首先,用户提到的“Byte文件读写”应该是指以字节为单位或者处理字节数组的读写Java中的字节流主要是InputStream和OutputStream这两个抽象,以及它们的子,比如FileInputStream和FileOutputStream,这些可以处理字节数据。另外,可能还会用到BufferedInputStream和BufferedOutputStream来提高效率,毕竟它们有缓冲区。 然后,用户可能需要读取文件到字节数组,或者将字节数组写入文件。比如,FileInputStream的read方法可以读取字节到byte数组,而FileOutputStream的write方法可以写入byte数组到文件。此外,Files工具里的readAllBytes和write方法可能更简洁,但需要确认Java版本是否支持,比如Java 7及以上。 还要考虑大文件的情况,一次性读取可能内存不够,这时候需要用循环读取的方式,分块处理。比如用while循环,每次读取一定大小的字节,直到读完。同时,使用缓冲流可以减少IO次数,提升性能。 用户可能还会需要一些示例代码,比如如何读取文件到byte数组,如何写入byte数组到文件,还有如何处理大文件的分块读写。需要确保代码中正确使用了try-with-resources语句,自动关闭流,避免资源泄漏。 另外,可能要注意异常处理,比如IOException,在示例中应该捕获并处理。还要提醒用户注意字符编码的问题,虽然这里是字节操作,但如果涉及到从字节转换到字符串,需要正确指定编码,比如UTF-8。 有没有其他相关的或方法?比如ByteArrayInputStream和ByteArrayOutputStream,虽然这些更多是处理内存中的字节数组,但可能在某些场景下有用。不过用户的问题主要是文件读写,所以重点还是在文件流上。 还要参考用户提供的引用内容,里面提到了FileInputStream和FileOutputStream的使用,还有HDFS的API,但用户现在需求是本地文件的字节读写,所以主要参考引用1和引用2中的示例。例如,引用1中的示例展示了使用FileOutputStream写入字节数据,以及FileInputStream读取字节到缓冲区。引用2中的代码也是用FileInputStream逐个字节读取,但用户可能需要的是读取整个byte数组或者分块读取。 总结下来,回答的结构应该是先介绍核心API,然后给出不同场景的示例,比如小文件、大文件、缓冲流的使用,可能还要提到NIO中的Files的方法。最后给出相关问题,帮助用户进一步学习。</think>### Java中使用Byte进行文件读写的API及方法 在Java中,字节级别的文件读写主要通过`InputStream`和`OutputStream`的子实现。以下是核心API及具体示例: --- #### 1. **基础API** - **`FileInputStream`**:用于从文件读取字节数据。 - **`FileOutputStream`**:用于向文件写入字节数据。 - **`BufferedInputStream`/`BufferedOutputStream`**:通过缓冲区提升读写效率。 - **`Files.readAllBytes()`**(Java 7+):直接读取文件到字节数组[^1][^2]。 --- #### 2. **示例代码** ##### (1) **写入字节到文件** ```java try (FileOutputStream fos = new FileOutputStream("output.txt")) { byte[] data = {72, 101, 108, 108, 111}; // "Hello"的ASCII码 fos.write(data); // 写入整个字节数组 fos.flush(); // 强制刷新缓冲区 } catch (IOException e) { e.printStackTrace(); } ``` ##### (2) **读取文件到字节数组** ```java try (FileInputStream fis = new FileInputStream("input.txt")) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { // 处理读取的字节(例如转换为字符串) String content = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8); System.out.println(content); } } catch (IOException e) { e.printStackTrace(); } ``` ##### (3) **使用缓冲流提升性能** ```java try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) { byte[] buffer = new byte[4096]; // 4KB缓冲区 int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); // 分块写入 } } catch (IOException e) { e.printStackTrace(); } ``` ##### (4) **Java 7+的简洁写法** ```java // 读取文件到字节数组 byte[] fileContent = Files.readAllBytes(Paths.get("input.txt")); // 写入字节数组到文件 Files.write(Paths.get("output.txt"), new byte[]{72, 101, 108, 108, 111}); ``` --- #### 3. **关键注意事项** - **大文件处理**:避免一次性读取大文件,使用分块读写(如示例3)。 - **字符编码**:字节与字符串转换时需明确编码(如`StandardCharsets.UTF_8`)。 - **资源管理**:优先使用`try-with-resources`自动关闭流[^1][^2]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值