Search code examples
javafileencodingrandomaccessfile

Read String with RandomAccessFile from file with different encoding


I have a big file encoded 1250. Lines are just single polish words one after another:

zając
dzieło
kiepsko
etc

I need to choose random 10 unique lines from this file in a quite fast way. I did this but when I print these words they have wrong encoding [zaj?c, dzie?o, kiepsko...], I need UTF8. So I changed my code to read bytes from file not just read lines, so my efforts ended up with this code:

public List<String> getRandomWordsFromDictionary(int number) {
    List<String> randomWords = new ArrayList<String>();
    File file = new File("file.txt");
    try {
        RandomAccessFile raf = new RandomAccessFile(file, "r");

        for(int i = 0; i < number; i++) {
            Random random = new Random();
            int startPosition;
            String word;
            do {
                startPosition = random.nextInt((int)raf.length());
                raf.seek(startPosition);
                raf.readLine();
                word = grabWordFromDictionary(raf);
            } while(checkProbability(word));
            System.out.println("Word: " + word);
            randomWords.add(word);
        }
    } catch (IOException ioe) {
        logger.error(ioe.getMessage(), ioe);
    }
    return randomWords;
}

private String grabWordFromDictionary(RandomAccessFile raf) throws IOException {
    byte[] wordInBytes = new byte[15];
    int counter = 0;
    byte wordByte;
    char wordChar;
    String convertedWord;
    boolean stop = true;
    do {
        wordByte = raf.readByte();
        wordChar = (char)wordByte;
        if(wordChar == '\n' || wordChar == '\r' || wordChar == -1) {
            stop = false;
        } else {
            wordInBytes[counter] = wordByte;
            counter++;
        }           
    } while(stop);
    if(wordInBytes.length > 0) {
        convertedWord = new String(wordInBytes, "UTF8");
        return convertedWord;
    } else {
        return null;
    }
}

private boolean checkProbability(String word) {
    if(word.length() > MAX_LENGTH_LINE) {
        return true;
    } else {
        double randomDouble = new Random().nextDouble();
        double probability = (double) MIN_LENGTH_LINE / word.length();
        return probability <= randomDouble;         
    }
}

But something is wrong. Could you look at this code and help me? Maybe you see some obvious errors but not obvious for me? I will appreciate any help.


Solution

  • Your file is in 1250, so you need to decode it in 1250, not UTF-8. You can save it as UTF-8 after the decoding process though.

    Charset w1250 = Charset.forName("Windows-1250");
    convertedWord = new String(wordInBytes, w1250);