I'm trying to read one line at a time from a .txt using FileInputStream.

FileInputStream in = null;
            
// Open an input stream

in = new FileInputStream("out.txt");

int c;

while ( (c = in.read() )!= -1 )
               
     textArea2.append(new DataInputStream(in).readLine() );

in.close();

For this out.txt:

abc abc
lalala xyxy

It displays:

bc abcbc abcalala xyxy

How can I fix it ?

Recommended Answers

All 2 Replies

A general comment on your coding style:
Instead of chaining all those constructors and methods in one statement, break them up into separate single steps. I'm not sure what your mess of code does with creating a new DataInputStream object every time around the loop.

The reason the first 'a' is missing is that it was read in the c variable and ignored.

To read Strings from a text file, use a BufferedReader class wrapped around a FileReader object. It has a method that makes it very easy to read lines from a text file.
Another possibility is to use the Scanner class. It has lots of methods to read different data from a file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.