Skip to content

ByteBuffer & FileChannel 이용해볼 것 #68

@occidere

Description

@occidere

ByteBuffer & FileChannel 이용해볼 것

ByteBuffer.allocateDirect(int size) 를 이용한 다이렉트 버퍼를 적용하면 BufferedOutputStream 등 보다 훨씬 빠르게 진행 가능

참고

private void useByteBuffer() throws Exception {
    String url = "https://github.com/occidere/MMDownloader/releases/download/v0.5.0.6/MMDownloader_0.5.0.6_Mac_Linux.zip";

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", "Mozilla/5.0");

    File file = new File("C:/Users/occid/Desktop/test1.zip");
		
    InputStream in = conn.getInputStream();
    FileChannel outChannel = new FileOutputStream(file).getChannel();
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);

    long et, st = System.currentTimeMillis();
    int read = 0;
    while ((read = in.read()) != -1) {
        if (!buf.hasRemaining()) {
	    buf.flip();
	    outChannel.write(buf);
	    buf.clear();
        }
        buf.put((byte) read);
    }
    buf.flip();
    outChannel.write(buf);
    outChannel.close();
    et = System.currentTimeMillis();

    System.out.println("ByteBuffer: " + (et - st) + " ms");
}

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions