【发布时间】:2018-04-21 08:53:11
【问题描述】:
我目前正在用 Java 练习文件处理,因此我尝试创建一种方法,该方法将使用 writeUTF() 和其他写入函数对文件上的用户输入进行编码。
我的代码如下所示:
public static void writeInfo(File file, int id, String name, int age) throws FileNotFoundException{
DataOutputStream dataOut = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream(file, true)));
try{
dataOut.writeInt(id);
dataOut.writeUTF(name);
dataOut.writeInt(age);
dataOut.close();
}catch(FileNotFoundException ex){
System.err.println("File not found !");
}catch(IOException ex){
System.err.println("Error writing in file !");
}finally{
try{
dataOut.close();
}catch(IOException ex){
System.err.println(ex);
}
}
}
现在我的问题是,在有多个输入后,我无法打印出一组特定的值。例如,如果我有 3 组输入:
ID - 3 名字 - 王牌 年龄 - 20
ID - 8 姓名 - 玛丽 年龄 - 22
ID - 5 姓名 - 卡尔 年龄 - 25
如果我想找到 ID 值为 5 的输入集,输出应该是:
ID - 5
Name - Karl
Age - 25
但我总是在运行后得到一个 EndOfFileException。
这是我如何找到特定值的代码:
public static void readID(File file, int id) throws FileNotFoundException{
DataInputStream dataIn = new DataInputStream(new
BufferedInputStream(new FileInputStream(file)));
try{
while(dataIn.available()>0){
if(dataIn.readInt() != id){
dataIn.read();
continue;
}else{
System.out.println("ID : " + dataIn.readInt());
System.out.println("Name : " + dataIn.readUTF());
System.out.println("Age : " + dataIn.readInt());
System.out.println("\n");
}
}
}catch(FileNotFoundException e){
System.err.println("File not found !");
}catch(IOException e){
System.err.println(e);
}finally{
try{
dataIn.close();
}catch(IOException ex){
System.err.println(ex);
}
}
我还尝试了不同的方法,例如将我首先读取的值包含到变量中。我知道我做错了什么,但仍在网上寻找解决方案。但我希望你们能帮助我,这样我仍然可以了解更多。
【问题讨论】:
标签: java file-handling