• java IODemo


    关键代码:
            RandomAccessFile file = new RandomAccessFile("temp.dat", "rw");

            file.writeBoolean(true);

            file.writeInt(100);

            file.writeInt(12345);

            file.writeInt(6789);

            file.seek(5);

    write(int), writeInt(int) 的区别

    在java DataOutputStream 中,定义的2个方法 write(int), writeInt(int), 它们接收的参数都是 int,但却有着本质的区别。

    write(int) 

    write(int) 继承自父类OutputStream,接收的虽然是int, 但是它只向输出流里写一个字节。我们知道,在java中,一个int 数子是4个字节组成,write(int) 只写入int的最低位的一个字节,其它3个字节被抛弃。

    例如: write(-100),

    int -100  的32位二进制码为:  11111111_11111111_11111111_10011100

    那么, write(-100),实际上只写了最低的8位到输出流:10011100。

    writeInt(int)

    writeInt(int),是把整个32位都写入输出流。 

    那么, write(-100),写了32位到输出流:11111111_11111111_11111111_10011100。

    file.seek()

    将文件游标移动到文件的任意位置,本文具体的file.seek()文件游标移动操作方法、

    package Campus;
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    
    public class IOTest {
    
        public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
            RandomAccessFile file = new RandomAccessFile("temp.dat", "rw");
            file.writeBoolean(true);
            file.writeInt(100);
            file.writeInt(12345);
            file.writeInt(6789);
            try {
                for (int i = 0; i < 100; i++){
                    file.seek(i);
                    System.out.println(i+":"+file.readInt());
                }
                
            } catch (Exception e) {
                // TODO: handle exception
                System.out.println("--");
            }
        }
    
    }
    

      运行结果:

      boolean占1字节,int占4字节,从低到高排列;最后一个是结束位。

    0:16777216
    1:100
    2:25600
    3:6553600
    4:1677721648
    5:12345
    6:3160320
    7:809041920
    8:956301338
    9:6789
    10:1737984
    11:444923904
    12:-2063597568
    13:1 //估计是结束字符的位置
    --

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            StringBuffer buffer = new StringBuffer();
            int value = 18;
            do {
                int temp = value & 0x07;
                System.out.println(temp);
                buffer.append(temp);
                System.out.println(value);
            }while ((value >>>= 3) != 0 );
            System.out.println(buffer.reverse());
        }
    

      输出结果:

    2
    18
    2
    2
    22

  • 相关阅读:
    bus总线
    vue 动态组件、父子组件传参
    echarts
    记录板
    留言板
    如何移除双系统mac中的windows系统
    Kernel,Shell,Bash 的关系
    zju 校队选拔 被虐记
    COGS 2638. 数列操作ψ 线段树
    退役公告【现已复活】
  • 原文地址:https://www.cnblogs.com/smuxiaolei/p/7736212.html
Copyright © 2020-2023  润新知