import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileTest {
public static void main(String[] args) {
try {
new FileTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileTest() throws Exception {
String pathIn = "D:/code/file.txt";
String pathOut = "D:/code/copy.txt";
FileChannel fcIn = new RandomAccessFile(pathIn, "rw").getChannel();
System.out.println("源文件总长度:" + fcIn.size());
System.out.println("源文件全部内容:");
printer(pathIn);
FileChannel fcOut = new FileOutputStream(pathOut).getChannel();
final int capacity = 4;
ByteBuffer buffer = ByteBuffer.allocate(capacity);
int count = 0;
while (true) {
count = fcIn.read(buffer);
if (count == -1) {
break;
}
buffer.flip();
fcOut.write(buffer);
buffer.clear();
}
System.out.println("复制文件总长度:" + fcOut.size());
System.out.println("复制文件全部内容:");
printer(pathOut);
}
// 打印path指向的文件中的内容。
private void printer(String path) throws Exception {
InputStream is = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s = null;
while (true) {
s = br.readLine();
if (s != null)
System.out.println(s);
else
break;
}
br.close();
is.close();
}
}
运行后输出:
源文件总长度:10
源文件全部内容:
0123456789
复制文件总长度:10
复制文件全部内容:
0123456789
上面是常规的文件复制,包含对源文件的读,以及把读出来的文件写入到目标复制文件。在Java NIO中,用FileChannel复制文件有更简单的方案,一行代码实现,如下:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class FileTest {
public static void main(String[] args) {
try {
new FileTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileTest() throws Exception {
String pathIn = "D:/code/file.txt";
String pathOut = "D:/code/copy.txt";
FileChannel fcIn = new RandomAccessFile(pathIn, "rw").getChannel();
System.out.println("源文件总长度:" + fcIn.size());
System.out.println("源文件全部内容:");
printer(pathIn);
FileChannel fcOut = new FileOutputStream(pathOut).getChannel();
// FileChannel方式的复制,一行代码实现。
fcIn.transferTo(0, fcIn.size(), fcOut);
System.out.println("复制文件总长度:" + fcOut.size());
System.out.println("复制文件全部内容:");
printer(pathOut);
}
// 打印path指向的文件中的内容。
private void printer(String path) throws Exception {
InputStream is = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s = null;
while (true) {
s = br.readLine();
if (s != null)
System.out.println(s);
else
break;
}
br.close();
is.close();
}
}