使用Java

时间:2015-08-27 15:45:18

标签: java performance io

我有一个10GB的PDF文件,我希望将其分成10个文件,每个文件大小为1GB。我需要并行执行此操作,这意味着旋转10个线程,每个线程从不同的位置开始,读取1GB的数据并写入文件。基本上最终结果应该是10个文件,每个文件包含原始10GB文件的一部分。

我查看了FileChannel,但是该位置是共享的,所以一旦我在一个线程中修改位置,它就会影响另一个线程。我还查看了Java 7中的AsynchronousFileChannel,但我不确定这是否可行。我对此问题的任何建议表示赞赏。

我写了这个简单的程序,它读取一个小文本文件来测试FileChannel的想法,似乎不适用于我想要实现的目标。

package org.cas.filesplit;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ConcurrentRead implements Runnable {

    private int myPosition = 0;
    public int getPosition() {
        return myPosition;
    }

    public void setPosition(int position) {
        this.myPosition = position;
    }

    static final String filePath = "C:\\Users\\temp.txt";

    @Override
    public void run() {
        try {
            readFile();
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }

    private void readFile() throws IOException {
        Path path = Paths.get(filePath);

        FileChannel fileChannel = FileChannel.open(path);
        fileChannel.position(myPosition);
        ByteBuffer buffer = ByteBuffer.allocate(8);
        int noOfBytesRead = fileChannel.read(buffer);

        while (noOfBytesRead != -1) {   
            buffer.flip();  
            System.out.println("Thread - " + Thread.currentThread().getId());
            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }

            System.out.println(" ");
            buffer.clear();         
            noOfBytesRead = fileChannel.read(buffer);
        }
        fileChannel.close();
    }   
}

0 个答案:

没有答案
相关问题