【发布时间】:2015-03-06 23:33:16
【问题描述】:
假设您有一个二进制文件,其中包含类型为 int 或 double 的数字。您不知道文件中数字的顺序,但它们的顺序记录在文件开头的字符串中。该字符串由字母 i (表示 int)和 d (表示 double)组成,按后续数字的类型顺序排列。字符串是使用 writeUTF 方法写入的。
例如字符串“iddiiddd”表示该文件包含八个值,如下:一个整数,后跟两个双精度数,后跟两个整数,后跟三个双精度数。
我的问题是,如果字符串中的字母多于数字,我如何创建一个 if 语句告诉用户他们试图读取的文件中有错误?
我试过用这个,其中“count”是数字的数量,“length”是字符串的长度,但这不起作用。
if(count!=length){
System.out.println("Error in file: Length of string and numbers are not equal");
System.exit(0);
}
我的其余代码是这样的:
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.print("Input file: ");
String fileName=keyboard.next();
int int_num_check=0;
double double_num_check=9999999999999999999999999999.999999999;
int int_num=0;
double double_num=0.0;
int count=0;
try{
FileInputStream fi=new FileInputStream(fileName);
ObjectInputStream input=new ObjectInputStream(fi);
String word=input.readUTF();
int length=word.length();
for(int i=0;i<length;i++){
if(word.charAt(i)=='i'){
int_num=input.readInt();
System.out.println(int_num);
if(int_num>int_num_check){
int_num_check=int_num;
}
}
else if(word.charAt(i)=='d'){
double_num=input.readDouble();
System.out.println(double_num);
if(double_num<double_num_check){
double_num_check=double_num;
}
}
else{
System.out.println("Error");
System.exit(0);
}
count++;
}
System.out.println("count: "+count);
System.out.println("length "+length);
if(count!=length){
System.out.println("Error in file: Length of string and numbers are not equal");
System.exit(0);
}
String checker=input.readUTF();
if(!checker.equals(null)){
System.out.println("Error");
System.exit(0);
}
input.close();
fi.close();
}
catch(FileNotFoundException e){
System.out.println("Error");
System.exit(0);
}
catch(EOFException e){
System.out.println("Largest integer: "+int_num_check);
System.out.println("Smallest double: "+double_num_check);
System.exit(0);
}
catch(IOException e){
System.out.println("Error");
System.exit(0);
}
}
}
【问题讨论】:
-
除非我弄错了,否则当没有更多要阅读的内容时,您的应用程序将在
input.readInt();(或双倍)处抛出异常。发生这种情况时,您可以捕获异常并进行处理。 -
我已经包含了我能想到的所有异常,只是当我测试这个程序并期望出现错误时我没有得到错误,我想知道为什么我没有得到一个?
-
你能发布文件的内容吗?
-
文件显示“idid 8 4.33316 2”@MateusViccari
-
它是用 ObjectOutputStream 编写的。它不是我自己写的,它是给我的,用于为即将到来的测试练习我的代码@MateusViccari
标签: java if-statement binaryfiles