PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

[FIXED] why does readLong method cause EOFException?

 October 29, 2022     binary, eof, io, java     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing