【问题标题】:Can someone walk me through this java code?有人可以引导我完成这个 java 代码吗?
【发布时间】:2014-12-07 18:53:44
【问题描述】:

我很难理解这个 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();
       }
}

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

【问题讨论】:

  • SO 不适用于此类问题
  • 此问题 ID 适合在 SO 网络进行代码审查。
  • 这个问题对其当前形式的其他人没有用处。请选择您希望回答的具体问题,以及显示您的问题的示例。

标签: java inputstream bufferedreader fileoutputstream


【解决方案1】:

一个 int 是 4 个字节。所以第一个 int 可以在文件中的位置 0 处读取。然后 2*4 将是下一个 int 的第一个字节,依此类推。您可以循环 n*4 其中 n 是要读取的整数。不过,您需要确保您正在读取整数,否则您将遇到未定义的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2016-04-28
    • 1970-01-01
    相关资源
    最近更新 更多