1. 将数据写进文件
public class NioFileChannelDemo1 {
public static void main(String[] args) throws Exception {
String str = "hello world";
FileOutputStream fileOutputStream = new FileOutputStream("路径/文件名.后缀");
FileChannel fileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put(str.getBytes(StandardCharsets.UTF_8));
byteBuffer.flip();
fileChannel.write(byteBuffer);
fileOutputStream.close();
}
}
2. 从文件中读取数据
public class NioFileChannelDemo2 {
public static void main(String[] args) throws Exception {
File file = new File("路径/文件名.后缀");
FileInputStream inputStream = new FileInputStream(file);
FileChannel fileChannel = inputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
fileChannel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()));
inputStream.close();
}
}
3. 拷贝文件
3.1 方式一
public class NioFileChannelDemo3 {
public static void main(String[] args) throws Exception {
FileInputStream inputStream = new FileInputStream("路径/源文件名.后缀");
FileChannel fileChannel1 = inputStream.getChannel();
FileOutputStream outputStream = new FileOutputStream("路径/拷贝后文件名.后缀");
FileChannel fileChannel2 = outputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
while (true) {
byteBuffer.clear();
int read = fileChannel1.read(byteBuffer);
if (read == -1) {
break;
}
byteBuffer.flip();
fileChannel2.write(byteBuffer);
}
inputStream.close();
outputStream.close();
}
}
3.2 方式二
public class NioFileChannelDemo4 {
public static void main(String[] args) throws Exception {
FileInputStream inputStream = new FileInputStream("路径/源文件名.后缀");
FileOutputStream outputStream = new FileOutputStream("路径/拷贝后文件名.后缀");
FileChannel sourceCh = inputStream.getChannel();
FileChannel destch = outputStream.getChannel();
destch.transferFrom(sourceCh, 0, sourceCh.size());
sourceCh.close();
destch.close();
inputStream.close();
outputStream.close();
}
}
3.3 方式三
public class NioFileChannelDemo5 {
public static void main(String[] args) throws IOException {
File source = new File("路径/源文件名.后缀");
File dest = new File("路径/拷贝后文件名.后缀");
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
inChannel = new FileInputStream(source).getChannel();
outChannel = new FileOutputStream(dest).getChannel();
MappedByteBuffer buf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
outChannel.write(buf);
inChannel.close();
outChannel.close();
}catch(Exception e){
e.printStackTrace();
} finally {
inChannel.close();
outChannel.close();
}
}
}