java - 从具有不同编码的文件中使用 RandomAccessFile 读取字符串

标签 java file encoding randomaccessfile

我有一个编码为 1250 的大文件。行只是一个接一个的波兰语单词:

zając
dzieło
kiepsko
etc

我需要以相当快的方式从此文件中随机选择 10 行。我这样做了,但是当我打印这些词时,它们的编码有误 [zaj?c, dzie?o, kiepsko...],我需要 UTF8。所以我更改了我的代码以从文件中读取字节而不仅仅是读取行,所以我的努力​​最终得到了这段代码:

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;         
    }
}

但是有一点不对。你能看看这段代码并帮助我吗?也许你看到一些明显的错误但对我来说并不明显?我将不胜感激任何帮助。

最佳答案

你的文件是1250的,所以你需要用1250解码,而不是UTF-8。不过,您可以在解码过程后将其保存为 UTF-8。

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

关于java - 从具有不同编码的文件中使用 RandomAccessFile 读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13869263/

相关文章:

java - 在使用 2 个分区创建的 Azure 事件中心中,事件中心使用者尝试连接到第 3 个和第 4 个分区

c++ - 打开文件 C++ 时出现问题

file - Haskell 延迟打开和关闭文件

C++ 将数据从 std::string 复制到 std::wstring

python - 如何将 python 字符串转换为 ucs2 十六进制?

java - 当我的子类位于不同的包中时,为什么我的子类无法访问其父类(super class)的 protected 变量?

java - 修改 JSTL 导入标记以在 JSP 中显示 gzip 压缩文本

java - 有没有类似于 Windows 资源管理器的布局?

java - 如何使用文件读取器和字符数组拼凑字符串

c++ - 在 boost.spirit 中编码