|
| 1 | +package org.javacore.nio; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.FileOutputStream; |
| 6 | +import java.io.IOException; |
| 7 | +import java.nio.ByteBuffer; |
| 8 | +import java.nio.channels.FileChannel; |
| 9 | +/* |
| 10 | + * Copyright [2015] [Jeff Lee] |
| 11 | + * |
| 12 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 13 | + * you may not use this file except in compliance with the License. |
| 14 | + * You may obtain a copy of the License at |
| 15 | + * |
| 16 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 17 | + * |
| 18 | + * Unless required by applicable law or agreed to in writing, software |
| 19 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 20 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 21 | + * See the License for the specific language governing permissions and |
| 22 | + * limitations under the License. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @author Jeff Lee |
| 27 | + * @since 2015-10-9 17:38:08 |
| 28 | + * FileChannel的文件复制案例 |
| 29 | + */ |
| 30 | +public class ChannelCopy { |
| 31 | + // 读取的文件 |
| 32 | + private static final String sourceFile = |
| 33 | + "src" + File.separator + |
| 34 | + "org" + File.separator + |
| 35 | + "javacore" + File.separator + |
| 36 | + "nio" + File.separator + |
| 37 | + "ChannelCopy.java"; |
| 38 | + // 输出的文件 |
| 39 | + private static final String targetFile = "data.txt"; |
| 40 | + |
| 41 | + private static final int BSIZE = 1024; // 1K字节 |
| 42 | + |
| 43 | + @SuppressWarnings("resource") |
| 44 | + public static void main(String[] args) throws IOException { |
| 45 | + // 创建用于读写的Channel |
| 46 | + FileChannel |
| 47 | + in = new FileInputStream(sourceFile).getChannel(), |
| 48 | + out = new FileOutputStream(targetFile).getChannel(); |
| 49 | + |
| 50 | + // 分配ByteBuffer的大小 1K |
| 51 | + ByteBuffer buffer = ByteBuffer.allocate(BSIZE); |
| 52 | + // 将字节序列从此通道读入给定的缓冲区,分块读,直至读到文件末端 |
| 53 | + while (in.read(buffer) != -1) {// -1,表示读到文件末端 |
| 54 | + // 反转缓冲区,为写入或读取做好准备 |
| 55 | + buffer.flip(); |
| 56 | + // 将含有字节序列的缓冲区写入文件通道 |
| 57 | + out.write(buffer); |
| 58 | + // 清空缓冲区 |
| 59 | + buffer.clear(); |
| 60 | + } |
| 61 | + |
| 62 | + } |
| 63 | +} |
0 commit comments