可以通过FileInputStream、FileOutputStream来实现,这里就不说了。
FileChannel
//打开文件,只读模式
FileChannel in = FileChannel.open(Paths.get("tt"),StandardOpenOption.READ);
//打开文件,写模式,没有就创建
FileChannel out = FileChannel.open(Paths.get("ttout"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);
ByteBuffer bf = ByteBuffer.allocate((int) in.size());
//读到bf中
in.read(bf);
//切换模式
bf.flip();
//写入文件
out.write(bf);
in.close();
out.close();
//内存映射文件,
//如果文件的大小超过2G,一般建议建立多个映射
FileChannel channel = new FileInputStream("tt").getChannel();
FileChannel channel2 = new FileOutputStream("tt6out").getChannel();
MappedByteBuffer mp = channel.map(MapMode.READ_ONLY, 0, channel.size());
channel2.write(mp);
channel.close();
channel2.close();
FileChannel channel = new FileInputStream("tt").getChannel();
FileChannel channel2 = new FileOutputStream("tt6out").getChannel();
channel.transferTo(0,channel.size(), channel2);
channel.close();
channel2.close();
File类
Path path1 = Paths.get("D:\\123");
Path path2 = Paths.get("D:\\", "123","456.txt");
Files.createDirectories(path1);
if(!Files.exists(path2)) {
//创建文件
Files.createFile(path2);
}
Files.copy(new FileInputStream(new File("D:\\123\\456.txt")), Paths.get("D:\\", "123","222.txt"));
Files.copy(path2, new FileOutputStream(new File("D:\\123\\789.txt")));
Files.copy(path2, Paths.get("D:\\", "123","111.txt"));
List<String> list = Files.readAllLines(Paths.get("tt"));
Files.write(Paths.get("tt7"), list);