File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Filereader - Reading >1 char at a time Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Filereader - Reading >1 char at a time" Watch "Filereader - Reading >1 char at a time" New topic

Filereader - Reading >1 char at a time

richard gallagher

Joined: Mar 15, 2008
Posts: 9
Hi all,

- This question relates to using a text file to create a game map.
- My current code reads 1 character at a time.

- Is it possible for the filereader to read 2 characters at once?
- Example -

This way, each "x,y" coordinate (tile) can have more than 1 image at loadup. (using only alpahbet and numerics etc is too limiting)


[ March 16, 2008: Message edited by: richard gallagher ]
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
Originally posted by richard gallagher:


Don't use == to test Strings for equality; use the String class equals() method.
Use "" round Strings, not ''. That code snippet won't compile because of the ''. You can't get two keystrokes into a char like that.

You can read a whole line with a Buffered Reader, or you can use the Scanner class to read a line. A Scanner will read the next char, int, etc., instead if you ask nicely (nextInt() etc), so lots of people use Scanner for simple text files instead of Readers.

You can split the line into a char[] array with a method of the String class (look through the API; it has an obvious name). You could use the charAt() method of String to find different chars within a String instead.

Don't use a break like that. Declare a String line, thenwill take care of the reading. You need the extra pair of () to force the = operator to be executed before the != because = has a very low precedence.

Your closing the reader leaves you open to resource leaks if there is an exception. You should use something like this which ensures the reader closes even if there is an IOExceptionThe "finally" will make sure to execute that block of code; the != null bit makes sure you only close the reader if it was opened in the first place, and the outer try . . . catch will handle the exceptions.

If you use a Scanner, it consumes Exceptions, but you can get the Exception with its IOException() method.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
On reading my last post I notice an error; there is a ) missing from the line starting "while ((line = reader.nextLine()." Sorry.
Also the comment about closing the FileReader only applies of you say
I agree. Here's the link:
subject: Filereader - Reading >1 char at a time
jQuery in Action, 3rd edition