在Java中处理大型Textfiles

Rob*_*bin 5 java text nio

我想知道如果我们假设Filesize大于内存,你如何在Java中操作大文本文件.我搜索了该主题,它表明大多数人都推荐java.nio这样的任务.

不幸的是,我没有找到任何关于如何操作文件的文档.例如,读取每一行,修改它,写它.我尝试过类似的东西,但这不起作用:

    FileChannel fileChannel = null;
    try {
        fileChannel = new RandomAccessFile(file, "rw").getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(256);

        while (fileChannel.read(buffer) != -1) {
            buffer.rewind();
            buffer.flip();
            String nextLine = buffer.asCharBuffer().toString();
            if (replaceBackSlashes) {
                nextLine = nextLine.replace("\\\\", "/");
            }
            if (!(removeEmptyLines && StringUtils.isEmpty(nextLine))) {
                buffer.flip();
                buffer.asCharBuffer().put(nextLine);
            }

            buffer.clear();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

那你有什么建议?String nextline也与我文件中的任何内容都不匹配.也许我需要设置编码?

xag*_*gyg 7

逐行.像这样......

public static void main(String[] args) throws Exception {

    File someFile = new File("someFile.txt");
    File temp = File.createTempFile(someFile.getName(), null);
    BufferedReader reader = null;
    PrintStream writer = null;

    try {
        reader = new BufferedReader(new FileReader(someFile));
        writer = new PrintStream(temp);

        String line;
        while ((line = reader.readLine())!=null) {
            // manipulate line
            writer.println(line);
        }
    }
    finally {
        if (writer!=null) writer.close();
        if (reader!=null) reader.close();
    }
    if (!someFile.delete()) throw new Exception("Failed to remove " + someFile.getName());
    if (!temp.renameTo(someFile)) throw new Exception("Failed to replace " + someFile.getName());
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你的 `catch` 块所做的只是重新抛出,你可以只使用 `try-finally` 构造并完全省略 catch 块:) (2认同)