tags:

views:

277

answers:

4

I have a file saved as utf-8 (saved by my application in fact). How do you read it character by character?

File file = new File(folder+name);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);

The two options seem to be:

char c = dis.readByte()
char c = dis.readChar()
  • The first option works as long as you only have ascii characters stored, ie english.
  • The second option reads the first and second byte of the file as one character.

The original file is being written as follows:

File file = File.createTempFile("file", "txt");
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
+2  A: 

Use a Reader (eg. BufferedReader)

Reader reader = new BufferedReader(new FileReader(file));

char c = reader.read();

objects
The problem with this is that the `Reader` will use the default character encoding of the platform you're running it on, which might not be UTF-8. Use `InputStreamReader` as dmazzoni suggests, this allows you to specify that UTF-8 must be used.
Jesper
Yes aware of that, but the file is being saved with the default encoding (by the same application). If UTF-8 is specifically needed then it should be specified in both places.
objects
I'd recommend specifying the encoding as UTF-8, both when reading and writing. That way there's no ambiguity and no possibility for mixups.
Sam Barnum
Yes I suggested specifying it in both places in my comment above (if UTF-8 is specifically needed)
objects
A: 

You can read individual bytes and when you hit a byte that is less than 128 (ie. the 8th byte is 0) then that is the last byte of the character.

I'm no Java expert, but I would assume that there are better ways. Maybe some way of telling the reader what encoding it is in...

edit: see dmazzoni's answer.

Tor Valamo
+7  A: 

You don't want a DataInputStream, that's for reading raw bytes. Use an InputStreamReader, which lets you specify the encoding of the input (UTF-8 in your case).

dmazzoni
`DataInputStream` is for reading class files. :)
Tom Hawtin - tackline
+3  A: 

You should be aware that in the Java world you use streams to process bytes, and readers/writers to process characters. These two are not the same, and you should choose the right one to handle what you have.

Have a look at http://java.sun.com/docs/books/tutorial/i18n/text/stream.html to see how to work with characters in a byte-oriented world.

The Sun Java Tutorial is a highly recommended learning resource.

Thorbjørn Ravn Andersen