0

I tried to read from a Textfile using DataInputStream and FileInputStream. I know i should use FileReader instead but i wanted to try it with Byte streams.

here is the code

import java.io.*;

public class FTest_3 {

public static void main(String[] args) throws IOException{
    DataInputStream stream = new DataInputStream(new FileInputStream("lol1.txt"));
    String str = stream.readUTF();
    System.out.println(str);
    stream.close();
}   
}

If i try to read from the file lol1.txt, getting EOF Exception and readUTf(unknownsource) errors.

But if I create a file lol1.txt using DataOutputStream and then read it using the above code, It works fine.

Here is my code to Write file

import java.io.*;

public class FTest_4 {

public static void main(String[] args) throws IOException{
    DataOutputStream stream = new DataOutputStream(new FileOutputStream("lol1.txt"));
    stream.writeUTF("hahah");
    stream.close();
 }  
}

Also I could not find any relevant post which could answer my query. Thanks!

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
lord_ozb
  • 95
  • 8
  • 1
    so how are you creating the file originally? – Scary Wombat May 09 '16 at 04:50
  • DataOutputStream uses a specific file format. You cannot really create the file some other way and expect to be able to read it. In particular, you cannot read text files with it. – Thilo May 09 '16 at 04:52
  • " i wanted to try it with Byte streams". Well, do that, then. A DataInputStream is not a byte stream. For raw bytes, use FileInputStream directly. – Thilo May 09 '16 at 04:53
  • I was creating file using notepad. sorry I'm new to java – lord_ozb May 09 '16 at 04:55
  • You can use the "read" method (on the FileInputStream) to read bytes from a file. – Thilo May 09 '16 at 05:01

2 Answers2

2

readUTF is not a general-purpose method to read Strings from text files.

It first reads two bytes that are supposed to contain the number of data bytes that follow (bytes, not characters). After that come the bytes for the string in a modified UTF-8 encoding.

In your case, you were probably reading the two ASCII characters "ha" (0x68 0x61) at the beginning of your file, which is a pretty big number when interpreted as an integer, and then got an EOF because there were not enough bytes left in the file to match that.

To read raw bytes, use one of the InputStream#read methods.

To read text files, use a Reader, not an InputStream. Then you can read Strings as well.

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656
0

Try to use stream.read(); for reading from a text file using DataInputStream or for specific values try to use stream.readDouble(), stream.readInt(), etc. and similarly try to use stream.write() for writing into a text file using DataOutputStream.

Deepanjan
  • 649
  • 2
  • 8
  • 15