Issue
It throws eof exception in line 10 when I execute the following code. It seems that it cannot execute the readLong method. What should I do?
try (DataOutputStream dataOutputStream=new DataOutputStream(new BufferedOutputStream(new
FileOutputStream("1.dat")));
DataInputStream dataInputStream=new DataInputStream(new BufferedInputStream(new
FileInputStream("C:\\Users\\Asus\\IdeaProjects\\Example" +
"\\1.dat")))){
dataOutputStream.writeLong(123);
dataOutputStream.writeChar('D');
dataOutputStream.writeUTF("Hello!");
System.out.println(dataInputStream.readLong());//exception occurse here
System.out.println(dataInputStream.readChar());
System.out.println(dataInputStream.readUTF());
}catch (IOException e){
e.printStackTrace();
}
Solution
the problem you are reading the file before writing on it. when you read the file it was empty. also the data are not saved to the file until the stream is closed. so if you want to read the written values you should close the input stream and then read the file. also be careful that the output stream file path is different than the input stream
here an example:
try ( DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("1.dat")))) {
dataOutputStream.writeLong(123);
dataOutputStream.writeChar('D');
dataOutputStream.writeUTF("Hello!");
dataOutputStream.close();
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream("1.dat")));
System.out.println(dataInputStream.readLong());
System.out.println(dataInputStream.readChar());
System.out.println(dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
Answered By - mss Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.