Skip to content

Instantly share code, notes, and snippets.

@hotstu
Created Jun 11, 2020
Embed
What would you like to do?
Java Nio File channel code including write/read/copy/lock/map
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class NioFile {
@Test
public void write() {
try (
RandomAccessFile file = new RandomAccessFile("test.out", "rw");
FileChannel channel = file.getChannel()
) {
for (int i = 0; i < 1000; i++) {
final ByteBuffer wrap = ByteBuffer.wrap("fork you\n".getBytes());
channel.write(wrap);
}
channel.force(true);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void read() {
try (
RandomAccessFile file = new RandomAccessFile("test.out", "rw");
FileChannel channel = file.getChannel();
final ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream()
) {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (channel.read(byteBuffer) > 0) {
byteOutputStream.write(byteBuffer.array(), 0, byteBuffer.position());
byteBuffer.clear();
}
System.out.println(new String(byteOutputStream.toByteArray()).length());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void copy() {
try (
RandomAccessFile file = new RandomAccessFile("test.out", "r");
RandomAccessFile file2 = new RandomAccessFile("test.out3", "rw");
FileChannel channel = file.getChannel();
FileChannel channel2 = file2.getChannel();
) {
channel2.truncate(0);
ByteBuffer byteBuffer = ByteBuffer.allocate(16);
while (channel.read(byteBuffer) > 0) {
byteBuffer.flip();
channel2.write(byteBuffer);
byteBuffer.flip();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 进程间: lock()将block,tryLock()返回null
* 线程间: lock()将block,tryLock()抛出异常
*/
@Test
public void lock() {
try (
RandomAccessFile file2 = new RandomAccessFile("test.out3", "rw");
FileChannel channel2 = file2.getChannel();
final FileLock lock = channel2.lock()
) {
Thread another = new Thread(() -> {
tryLock();
});
another.start();
Thread.sleep(15*1000);
System.out.println("lock released");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void tryLock() {
try (
RandomAccessFile file2 = new RandomAccessFile("test.out3", "rw");
FileChannel channel2 = file2.getChannel();
final FileLock lock = channel2.tryLock();
) {
System.out.println(lock);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void map() {
try (
RandomAccessFile file2 = new RandomAccessFile("test.out3", "rw");
FileChannel channel2 = file2.getChannel();
) {
final MappedByteBuffer map = channel2.map(FileChannel.MapMode.READ_WRITE, 0, 100);
//可以做多线程分段文件下载
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment