读写二进制文件

  1. 读二进制文件,保存在int数组中
import java.io.*;
public class Input2Buffer {

    public static void main(String[] args){
        int[] bits = getBits(NumOfByte);
           for (int i = 0; i < bits.length; i ++ ){
                System.out.print(bits[i] + ",");  
            }
    }

    public static int[] getBits(int numOfByte) {
        int NumOfByte = numOfByte;
        int[] byte2int = new int[NumOfByte];
        try {

            FileInputStream fis = new FileInputStream("test");
            BufferedInputStream bis=new BufferedInputStream(fis);
            DataInputStream dis = new DataInputStream(bis);
            byte[] buffer = new byte[NumOfByte];
            dis.read(buffer, 0, NumOfByte);
 
            int count = 0;
            int j = 0;
            while(count <NumOfByte){
                String aString = Integer.toBinaryString((buffer[count] & 0xFF) + 0x100).substring(1);
                byte2int[j] = Integer.parseInt(aString.substring(7,8));
                j++;
                count ++;
            }
            return byte2int;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byte2int;
    }

  1. 写入二进制文件
import java.io.*;

public class Write2File {
    public static void main(String[] args) {
        OutputStream os;
        FileOutputStream fos;
        File file = new File("test");
        try
        {
            os = new FileOutputStream(file);
            byte[] buf = new byte[]{1,0,1,0,0,1,1,1,0,1,0,1};
            BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(buf));
            while (is.read(buf) != -1) {
                os.write(buf);
            }
            os.flush();
            is.close();
            os.close();
        } catch (
                IOException e)

        {
            e.printStackTrace();
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容