The method reads the file symbolically. You need to pass this method to the parser so that it goes through all the characters. But since it returns a value, one character is naturally output.

public char read() throws ReadException { try { int symbol; fileRead = new BufferedReader(new FileReader(pathFile)); while ((symbol = fileRead.read()) != -1) { } return (char) symbol; } catch (IOException e) { throw new ReadException(e); } } 

Question: How can I pass it to the parser?

  • A question, and the parser accepts any interface? need more information, what kind of parser, etc. - andreich
  • Yes, it takes the interface. The problem is this: given * .java-file. It is necessary to go through the characters in the file ("{", ";") to format it. Put transfers and indents - Abraham

2 answers 2

Use an iterator . Implementation Sketch:

 class ReaderIterator implements Iterator<Character> { private final Reader reader; private int next = -1; public ReaderIterator(Reader reader) { this.reader = reader; } @Override public boolean hasNext() { if (next != -1) { return true; } else { try { next = reader.read(); return (next != -1); } catch (IOException e) { throw new ReadException(e); } } } @Override public Character next() { if (!hasNext()) { throw new NoSuchElementException(); } Character result = Character.valueOf((char)next); next = -1; return result; } } 

Then pass the iterator to the parser:

 fileRead = new BufferedReader(new FileReader(pathFile)); ReaderIterator iterator = new ReaderIterator(fileRead); parser.Parse(iterator); // Parse(Iterator<Character> iterator) 

In the parser we get the characters:

 while (iterator.hasNext()) { char c = iterator.next().charValue(); // ... } 

The disadvantage of the solution is that ReadException must be unchecked.

  • In fact, I have a task to invent a bicycle like my iterator, but your answer allowed me to get close - Abraham

Few details of the task. But, as an option, you can return an array:

 public char[] read() throws ReadException { try { int symbol; String s = ""; //тут лучше SbringBuilder использовать, String для краткости лишь fileRead = new BufferedReader(new FileReader(pathFile)); while ((symbol = fileRead.read()) != -1) { s += (char) symbol; } return s.toCharArray(); } catch (IOException e) { throw new ReadException(e); } } 
  • one
    thanks, thought) - Abraham