二进制与位运算有关
java常用数据类型与所占字节数
int 4个字节
long 8个字节
byte 1个字节
float 4个字节
char 2个字节
1个字节=8个二进制位
负数表示形式:
在计算机中,负数以其正值的补码形式表达
一个正数的二进制0与1交换,加上1,就是这个数的负数
二进制位运算在收藏的文章里有。。。。。
RandomAccessFile的使用
RandomAccessFile java提供的对文件内容的访问,既可以读文件,也可以写文件。
RandomAccessFile支持随机访问文件,可以访问文件的任意位置
(1)java文件模型
在硬盘上的文件是byte byte byte存储的,是数据的集合
(2)打开文件
有两种模式"rw"(读写) "r"(只读)
RandomAccessFile raf = new RandomeAccessFile(file,"rw")
文件指针,打开文件时指针在开头 pointer = 0;
(3) 写方法
raf.write(int)--->只写一个字节(后8位),同时指针指向下一个位置,准备再次写入
(4)读方法
int b = raf.read()--->读一个字节
(5)文件读写完成以后一定要关闭(Oracle官方说明)
代码:
public class Random_file {
public static void main(String[] args) throws IOException {
File file=new File("xbx.txt");
if (!file.exists()) {
file.createNewFile();
}
//RandomAccessFile只能写一个字节
RandomAccessFile accessFile=new RandomAccessFile(file, "rw");
int i=652323232;
//写字节 高八位
// accessFile.write(i);
//写int 全写进去
accessFile.writeInt(i);
//获取文件指针
System.out.println(accessFile.getFilePointer());
//指针设置为0
accessFile.seek(0);
//定义字节数组准备接收
byte[] bytes=new byte[(int)accessFile.length()];
//读取文件以字节形式存到字节数组中去
accessFile.read(bytes);
//遍历数组 输出
for (byte b : bytes) {
System.out.println(b);
}
}
}