【问题标题】:How to skip primitive data values while reading from file从文件读取时如何跳过原始数据值
【发布时间】:2016-02-28 11:34:18
【问题描述】:

我编写了一个从文件中读取整数的 Java 程序。之前使用以下代码将五个整数写入该文件:

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

现在在从 num.dat 文件中读取整数时,我希望跳过“n”个整数。我在另一个类中使用了以下代码:

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

只有当我请求文件的第一个整数时,程序才会显示正确的输出。如果我尝试跳过一些整数,它要么没有输出,要么输出错误。我在第一个程序中输入的整数不是一位数,而是三位整数。我还尝试跳过三位数整数的单个数字,但这也无济于事。请告诉我如何在读取原始数据值时跳过。

【问题讨论】:

  • 您能告诉我们您的输入以及错误和预期的输出吗?
  • 你能不能解释一下你为什么要这样做?
  • @Thorbjørn Ravn Anderson 我是新手。这是我在两天的文件 I/O 课程中所做的。

标签: java file fileinputstream datainputstream


【解决方案1】:
d.skip(n); //skips n integers

skip(long n) 方法的这种解释是不正确的:它跳过了n 字节,而不是n 整数:

跳过并丢弃输入流中的 n 字节数据。

要解决此问题,请编写您自己的方法,调用 d.readInt() n 次,并丢弃结果。您也可以不使用方法,只需添加一个循环即可:

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) {}

【讨论】:

  • 是的。 skip() 跳过字节。但由于我没有收到语法错误,我认为可能还有一个用于原始值的 skip() 方法。我会试试你说的话,让你知道。谢谢 :) 顺便说一句,如果 d.readInt() 被调用 n 次,我想跳到 5 个三位整数中的第三个,'n' 应该是什么?
  • @ProgyadeepMoulik Java 库的每个方法都有完整的文档记录。当您不确定某个方法的作用时,请查看其文档。当方法被继承时可能会很棘手,比如skip,因为DataInputStream 的文档页面上没有描述它。相反,所有继承方法的底部都有一个链接。您需要点击该链接以查看该方法的作用。
  • 感谢您的解决方案。它工作得很好。我刚刚调用了d.readInt() 的次数作为我想跳过的整数的数量。而且我还了解了RandomAccess 文件和类的seek() 方法,这有助于非常轻松地完成这项任务。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
  • 2018-08-20
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
相关资源
最近更新 更多