Reputation: 1795
Im learning java and currently studying Streams (Byte and Character), I wrote this code that writes an array in an .txt and then read's and prints the value written before. When compiling I have and error in the line 22 that says
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
heres the code:
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);
}
}
}
As I read the error, tried to delete the argument in readInt but I got an exception and not the output expected.
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);
}
}
}
with this I got this output:
writing: 2
writing: 5
writing: 3
writing: 6
writing: 4
writing: 7
writing: 4
writing: 8
Exception: java.io.EOFException
this is the output I want:
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
Upvotes: 1
Views: 394
Reputation: 31658
After you finish writing the file, you have to reset the file pointer back to the beginning.
..//write code for loop
rand.seek(0)
..//read code for loop
Upvotes: 2