- 读二进制文件,保存在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;
}
- 写入二进制文件
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();
}
}
}
网友评论