nio通道
Posted kill-9
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nio通道相关的知识,希望对你有一定的参考价值。
nio通道的创建方式一:
通过IO流创建nio通道package edzy.nio;
1 package edzy.nio;
2
3 import org.junit.Test;
4
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.nio.ByteBuffer;
9 import java.nio.MappedByteBuffer;
10 import java.nio.channels.FileChannel;
11 import java.nio.file.Paths;
12 import java.nio.file.StandardOpenOption;
13
14 public class Channel {
15
16 @Test
17 public void channel(){
18 FileInputStream fis = null;
19 FileOutputStream fos = null;
20 FileChannel in = null;
21 FileChannel out = null;
22
23 try{
24 fis = new FileInputStream("./src/main/java/edzy/nio/s.jpg");
25 fos = new FileOutputStream("./src/main/java/edzy/nio/sb.jpg");
26 in = fis.getChannel();
27 out = fos.getChannel();
28
29 ByteBuffer buf = ByteBuffer.allocate(1024);
30
31 while (in.read(buf) !=-1){
32
33 buf.flip();
34 out.write(buf);
35 buf.clear();
36 }
37
38
39
40 } catch (IOException e) {
41 e.printStackTrace();
42 } finally {
43
44 if (out != null){
45 try {
46 out.close();
47 } catch (IOException e) {
48 e.printStackTrace();
49 }
50 }
51
52 if (in != null){
53 try {
54 in.close();
55 } catch (IOException e) {
56 e.printStackTrace();
57 }
58 }
59
60 if (fos != null){
61 try {
62 fos.close();
63 } catch (IOException e) {
64 e.printStackTrace();
65 }
66 }
67
68 if (fis != null){
69 try {
70 fis.close();
71 } catch (IOException e) {
72 e.printStackTrace();
73 }
74 }
75 }
76 }
77 }
nio通道的创建方式二:
内存映射文件
1 package edzy.nio; 2 3 import org.junit.Test; 4 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.nio.ByteBuffer; 9 import java.nio.MappedByteBuffer; 10 import java.nio.channels.FileChannel; 11 import java.nio.file.Paths; 12 import java.nio.file.StandardOpenOption; 13 14 public class Channel { 15 16 @Test 17 public void channel(){ 18 FileChannel in = null; 19 FileChannel out = null; 20 try { 21 //使用FileChannel的open方法创建通道 22 in = FileChannel.open(Paths.get("./src/main/java/edzy/nio/s.jpg"), StandardOpenOption.READ); 23 out = FileChannel.open(Paths.get("./src/main/java/edzy/nio/s3.jpg"),StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE); 24 25 //内存映射文件 26 MappedByteBuffer mapIn = in.map(FileChannel.MapMode.READ_ONLY,0,in.size()); 27 MappedByteBuffer mapOut = out.map(FileChannel.MapMode.READ_WRITE,0,in.size()); 28 29 byte[] dest = new byte[mapIn.limit()]; 30 mapIn.get(dest); 31 mapOut.put(dest); 32 33 } catch (IOException e) { 34 e.printStackTrace(); 35 }finally { 36 if (in != null){ 37 try { 38 in.close(); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 44 if (out != null){ 45 try { 46 out.close(); 47 } catch (IOException e) { 48 e.printStackTrace(); 49 } 50 } 51 } 52 } 53 }
以上是关于nio通道的主要内容,如果未能解决你的问题,请参考以下文章