简体   繁体   English

FileInputStream使用read()跳过整数 - Java

[英]FileInputStream skipping Integers with read() - Java

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. 在搜索了一段时间的答案,并试图理解FileInputStream.read()和FileInputStream.available()之间的区别后,我仍然迷失了我编写的程序。

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()时,我从文件中获取完整的数组(10 20 30 40 50 60),但是当我使用read()时,我只获得了一半的数组(20 40 60)。

available() can read bytes whenever they're ready while read() blocks reading bytes until the fileOutputStream is finished with and closed. available()可以在它们准备就绪时读取字节,而read()会阻塞读取字节,直到fileOutputStream完成并关闭。 (Or I'm wrong?) (或者我错了?)

IF it is so, then why does it happen? 如果是这样,那为什么会发生?

Thanks! 谢谢!

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. read()没有任何问题,但是你在dataFromFile()中调用了两次(一次在while条件下,一次在循环内),因此跳过其他所有数字。 Do this instead: 改为:

int foo=0;
while ((foo=input.read()) != -1) {
   System.out.print(foo + " ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM