6

ファイルサイズがメモリよりも大きいと仮定すると、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();
            }
        }
    }

それで、あなたの推薦は何ですか?また、 Stringnextlineは、ファイル内の何にも一致しません。多分私はエンコーディングを設定する必要がありますか?

4

2 に答える 2

8

1行ずつ。このようなもの ...

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());
}
于 2013-01-08T13:19:34.877 に答える
2

素敵できれいな答えをくれたxagygに称賛を!以下はコメントに収まりませんでした:

すでに Java 7 を実行している場合は、処理ループにtry-with-resourcesを使用することで、多くのボイラープレート コードを節約できます。

File source = ...
File target = ...
try (BufferedReader in = new BufferedReader(new FileReader(source));
     PrintStream out = new PrintStream(target)) {
  String line;
  while ((line = in.readLine()) != null) {
    // manipulate line
    out.println(line);
  }
}
// no catch or finally clause!

Javaがinitalize-to-null-try-catch-finally-close-if-not-null面倒を見てくれます。コードが少なくなり、重要な呼び出しを忘れたり台無しにしたりする可能性が少なくなりclose()ます。

于 2013-01-08T13:35:15.093 に答える