美文网首页
读写二进制文件

读写二进制文件

作者: 发芽芽儿 | 来源:发表于2018-05-03 08:35 被阅读0次
  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();
        }
    }
}

相关文章

网友评论

      本文标题:读写二进制文件

      本文链接:https://www.haomeiwen.com/subject/lwtkrftx.html