javafilecharexternal-sorting

How can I read characters until a specific one in Java?


I want to read a few words from a file. I didn't found any method to do this, so I decided to read char by char, but I need to stop at the spaces to store the read word in my array and go to the next one.

I'm making an external sorting aplication, that's why I have a memory limitation, and, in that case, I can't just use readLine() and then split(), I need to have a control of what I read.

The read() method returns an int and I have no idea of what can I do to read() method return a char and stop reading after a space.

This is my code this far:

protected static String [] readWords(String arqName, int amountOfWords) throws IOException {
    FileReader arq = new FileReader(arqName);
    BufferedReader lerArq = new BufferedReader(arq);

    String[] words = new String[amountOfWords];

    for (int i = 0; i < amountOfWords; i++){
        //words[i] = lerArq.read();
    }

    return words;
}

Edit 1: I used a Scanner and the next() method, it worked. Scanner's initialization is at Main.

static String [] readWords(int amountOfWords, Scanner leitor) throws IOException {
    String[] words= new String[amountOfWords];

    for (int i = 0; i < amountOfWords; i++){
        words[i] = leitor.next();
    }

    return words;
}

Solution

  • If you want to read it char by char (so you have more control over what you want to store and what you don't), you could try something like this:

    import java.io.BufferedReader;
    import java.io.IOException;
    
    [...]
    
    public static String readNextWord(BufferedReader reader) throws IOException {
        StringBuilder builder = new StringBuilder();
    
        int currentData;
    
        do {
            currentData = reader.read();
    
            if(currentData < 0) {
                if(builder.length() == 0) {
                    return null;
                }
                else {
                    return builder.toString();
                }
            }
            else if(currentData != ' ') {
                /* Since you're talking about words, here you can apply
                 * a filter to ignore chars like ',', '.', '\n', etc. */
    
                builder.append((char) currentData);
            }
    
        } while (currentData != ' ' || builder.length() == 0);
    
        return builder.toString();
    }
    

    And then call it like this:

    String[] words = new String[amountOfWordsToRead];
    
    for (int i = 0; i < amountOfWordsToRead; i++){
        words [i] = readNextWord(yourBufferedReader);
    }