Question

After searching for an answer for a while, and trying to understand the difference between FileInputStream.read() and FileInputStream.available() I'm still lost with a program I've written.

public class Ex1plus2{
final static String fName= "1.dat";

public static void main(String[] args) throws FileNotFoundException,IOException {
    int[] a = new int[]{10, 20, 30, 40, 50, 60};
    //arrToFile(a);
    //arrFromFile();
    dataToFile(a);
    dataFromFile();
}

static void dataToFile(int[] a) throws IOException{
    //final String fName= "1.dat";
    try{
        File dataFile= new File (fName);
        FileOutputStream output=new FileOutputStream(dataFile);
        for (int i:a){
            output.write(i);
        }
        output.close();
    }
    catch(IOException ex){
        System.out.println("Oops! File not found...\n"
                + "System will now terminate itself");
        System.exit(0);

    }
}
static void dataFromFile() throws IOException{
    //final String fName= "1.dat";
    try{
    FileInputStream input= new FileInputStream(fName); 
    while(input.read()!=-1){
        System.out.print(input.read()+" ");
    }
    input.close();
    }
    catch(IOException ex){
        System.out.println("Oops! File not found...\n"
                + "System will now terminate itself");
        System.exit(0);


    }
}

When using available() I'm getting the full array from the file (10 20 30 40 50 60), but when I'm using read() I'm getting only half the array (20 40 60).

available() can read bytes whenever they're ready while read() blocks reading bytes until the fileOutputStream is finished with and closed. (Or I'm wrong?)

IF it is so, then why does it happen?

Thanks!

Était-ce utile?

La solution

There is nothing wrong with the read(), but you are calling it twice in dataFromFile() (once in the while condition and once inside the loop), hence the skipping of every other number. Do this instead:

int foo=0;
while ((foo=input.read()) != -1) {
   System.out.print(foo + " ");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top