2

I am currently trying to work with a custom text file to read quests for a small game, however i am having trouble getting the code to read each character, I've done my research and somehow come up with nothing. I am unsure of how to read a .txt file character by character, so if anyone can help or point me in the right direction it would be strongly appreciated.

xxKobalxx
  • 17
  • 1
  • 2
  • roughly... char c= (char) readByte(); – T McKeown Dec 27 '13 at 20:40
  • 2
    Maybe you can show us the code you have so far. – Pieter Dec 27 '13 at 20:41
  • Welcome to SO. Please read the [FAQ] and [Ask] before posting. In particular, you are required to show the code you have so far. – Jim Garrison Dec 27 '13 at 20:42
  • check out this post... Visit http://stackoverflow.com/questions/2597841/scanner-method-to-get-a-char – EricHansen Dec 27 '13 at 20:43
  • Take a look at the JavaDoc for the [FileReader](http://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html) class. In particular, the `read()` methods (although they return `int`s, they actually read `char`s so you can just cast the return values to `char`s). – daiscog Dec 27 '13 at 20:55

3 Answers3

3

If you want to read each character from file you could do something like this:

BufferedReader r=new BufferedReader(new FileReader("file.txt"));
int ch;
while((ch=r.read())!=-1){

// ch is each character in your file.

}

Good luck

solvator
  • 361
  • 1
  • 6
  • 12
2
Path path = Paths.get("filename");
    try (Scanner scanner =  new Scanner(path, ENCODING.name())){
      while (scanner.hasNextLine()){
        String s = scanner.nextLine();
        for(char c : s.toCharArray()) {
          // your code
      }      
    } catch(IOException e) {/* Reading files can sometimes result in IOException */}
1
File file = new File("text.txt");
Scanner in = new Scanner(file);

// option 1
while(in.hasNext())
{
 String temp = in.next();
 char[] temparr = temp.toCharArray();
 for(Character j: temparr)
 {
  //do someting....
 }
}
// or option 2
in.useDelimiter("");
while(in.hasNext())
{
  temp = in.next();
  //do something 
}

Option 1 gives you the ability to manipulate the string char by char if the condition is true.

Option just reads one char at a time and lets you preform an action but not manipulate the string found in the text file.

public void method() throws FileNotFoundException

if you dont want to use a try catch

drhunn
  • 319
  • 1
  • 2
  • 11