有人可以通过这个java代码告诉我吗?

时间:2014-12-07 18:53:44

标签: java inputstream bufferedreader fileoutputstream

我很难理解这个java程序是如何工作的。我知道我们有文件的I / O库。这是代码:

import java.io.*;

public class SimpleRandomAccessFile {
       public static void main(String[] args) throws IOException {
            RandomAccessFile inout = new RandomAccessFile("inout.dat", "rw");
            inout.setLength(0);

            for (int i = 0; i < 200; i++)
                    inout.writeInt(i);
            System.out.println("Current file length is " + inout.length());
            inout.seek(0);
            System.out.println("The first number is " + inout.readInt());

            inout.seek(2*4);
            System.out.println("The third number is " + inout.readInt());

            inout.seek(8*4);
            System.out.println("The ninth  number is " + inout.readInt());

            inout.writeInt(200);

            inout.seek(inout.length());
            inout.writeInt(1000);
            System.out.println("The new length is " + inout.length());

            inout.seek(9 * 4);
            System.out.println("The tenth number is " + inout.readInt());
            inout.close();
       }
}

任何帮助或反馈都会很棒!

1 个答案:

答案 0 :(得分:0)

int是4个字节。因此,第一个int可以在文件的第0位读取。那么2 * 4将是你下一个int的第一个字节,依此类推。你可以遍历n * 4,其中n是要读取的整数。您需要确保自己正在读取整数,否则您将遇到未定义的行为。