无法在Java中找出此RandomAccessFile代码的错误

时间:2015-12-15 04:03:01

标签: java

我正在学习java并且正在学习Streams(字节和字符),我写了这个代码,它在一个.txt中编写一个数组然后读取并打印之前写的值。当编译我有和错误的第22行说

method readInt in class RandomAccessFile cannot be applied to given types; 
d = rand.readInt(4*i);

required: no arguments 
foung: int
reason: actual and formal argument lists differ int length

继承人代码:

 import java.io.*;

        class Prueba7
        {
            public static void main(String args[])
            {
                int array[] = {2,5,3,6,4,7,4,8};
                int d;


                try(RandomAccessFile rand = new RandomAccessFile("prueba7.txt", "rw"))
                {
        for(int i: array)
                {
                    System.out.println("Writing: " +i);
                    rand.writeInt(i);
                }           

                for(int i = 0; i < array.length; i++)
                {

                    d = rand.readInt(4*i);
                    System.out.println("Reading file: ");
                    System.out.print(d);
                }
                }
                catch(IOException exc)
                {
                    System.out.println("Exception: " +exc);
                }
            }
        }

当我读到错误时,尝试删除readInt中的参数但是我得到了一个异常而不是预期的输出。

import java.io.*;

    class Prueba7
    {
        public static void main(String args[])
        {
            int array[] = {2,5,3,6,4,7,4,8};
            int d;


            try(RandomAccessFile rand = new RandomAccessFile("prueba7.txt", "rw"))
            {
    for(int i: array)
            {
                System.out.println("Writing: " +i);
                rand.writeInt(i);
            }           

            for(int i = 0; i < array.length; i++)
            {
                d = rand.readInt();
                System.out.println("Reading file: ");
                System.out.print(d);
            }
            }
            catch(IOException exc)
            {
                System.out.println("Exception: " +exc);
            }
        }
    }

有了这个,我得到了这个输出:

writing: 2
writing: 5
writing: 3
writing: 6
writing: 4
writing: 7
writing: 4
writing: 8
Exception: java.io.EOFException

这是我想要的输出:

writing: 2
writing: 5
writing: 3
writing: 6
writing: 4
writing: 7
writing: 4
writing: 8
Reading: 2 5 3 6 4 7 4 8

1 个答案:

答案 0 :(得分:2)

编写完文件后,必须将文件指针重置为开头。

..//write code for loop
rand.seek(0)

..//read code for loop