Reading file chunk by chunk

你。 提交于 2019-11-27 15:43:00

what you want is source data line. This is perfect for when your data is too large to hold it in memory at once, so you can start playing it before you receive the entire file. Or if the file never ends.

look at the tutorial for source data line here

http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read

I would use this FileInputSteam

See InputSteram.read(byte[]) for reading bytes at a time.

Example code:

try {
    File file = new File("myFile");
    FileInputStream is = new FileInputStream(file);
    byte[] chunk = new byte[1024];
    int chunkLen = 0;
    while ((chunkLen = is.read(chunk)) != -1) {
        // your code..
    }
} catch (FileNotFoundException fnfE) {
    // file not found, handle case
} catch (IOException ioE) {
    // problem reading, handle case
}

Instead of older io you can try nio for reading file chunk by chunk in memory not full file . You can use Channel to get datas from multiple source

RandomAccessFile aFile = new RandomAccessFile(
                        "test.txt","r");
        FileChannel inChannel = aFile.getChannel();
        long fileSize = inChannel.size();
        ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
        inChannel.read(buffer);
        //buffer.rewind();
        buffer.flip();
        for (int i = 0; i < fileSize; i++)
        {
            System.out.print((char) buffer.get());
        }
        inChannel.close();
        aFile.close();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!