I wrote a Java program that reads integers from a file. Five integers were written to that file earlier using the following code:
Scanner s=new Scanner(System.in);
DataOutputStream d=null;
System.out.println("Enter 5 integers");
try{
d=new DataOutputStream(new FileOutputStream("num.dat"));
for(int i=1;i<=5;i++){
d.writeInt(s.nextInt());
} //for
} //try
catch(IOException e){
System.out.println(e.getMessage());
System.exit(0);
}
finally{
try{
d.close()
}
catch(Exception e){}
}//finally
Now while reading the integers from the file num.dat, I wish to skip 'n' integers. I used the following code in another class:
DataInputStream d=null;
Scanner s=new Scanner(System.in);
int n=0; //stores no. of integers to be skipped
try{
d=new DataInputStream(new FileInputStream("num.dat");
for (...){
if(...)
n++; //condition to skip integers
} //for
}//try
catch(IOException e){
System.out.println(e.getMessage());
System.exit(0);
}
finally{
try{
d.skip(n); //skips n integers
System.out.println("Requested Integer is "+d.readInt());
d.close();
}
catch(Exception e) {}
} //finally
The program shows correct output only if I request the first integer of the file. If I try to skip some integers, it either gives no or a wrong output. The integers I entered in the first program weren't one digit but three digit integers. I also tried to skip individual digits of a three digit integer but that also didn't help. Please tell me how I can skip while reading primitive data values.
d.skip(n); //skips n integers
This interpretation of the skip(long n)
method is incorrect: it skips n
bytes, not n
integers:
Skips over and discards n bytes of data from the input stream.
To fix this problem, write your own method that calls d.readInt()
n
times, and discards the results. You could also do it without a method, simply by adding a loop:
try {
//skips n integers
for (int i = 0 ; i != n ; i++) {
d.readInt();
}
System.out.println("Requested Integer is "+d.readInt());
d.close();
}
catch(Exception e) {}