java 文件的复制方法
2017-02-19 14:34
316 查看
方法一、采用IO流的方法
public static void main(String[] args) {
int sum = countWordInFile("C://Users/diyvc/Desktop/test.txt", "a");
System.out.println(sum);
try {
fileCopy("C://Users/diyvc/Desktop/test.txt","C://Users/diyvc/Desktop/copy.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
/** * 文件复制方法1 * 方法名:文件复制 * 开发者:wangql * 开发时间:2017-2-18 */ public static void fileCopy(String source, String target) throws IOException { try (InputStream in = new FileInputStream(source)) { try (OutputStream out = new FileOutputStream(target)) { byte[] buffer = new byte[4096];//4096 = 4K,开辟4K的缓冲区 int bytesToRead; while((bytesToRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); } } } }方法二、采用NIO流的方法
/** * 文件复制方法2 * 方法名:文件复制 * 开发者:wangql * 开发时间:2017-2-18 */ public static void fileCopyNIO(String source, String target) throws IOException { try (FileInputStream in = new FileInputStream(source)) { try (FileOutputStream out = new FileOutputStream(target)) { FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(4096);//从堆空间中分配一个容量大小为capacity的byte数组作为缓冲区的byte数据存储器 while(inChannel.read(buffer) != -1) { buffer.flip(); outChannel.write(buffer); buffer.clear(); } } } }调用方法实现
public static void main(String[] args) {
int sum = countWordInFile("C://Users/diyvc/Desktop/test.txt", "a");
System.out.println(sum);
try {
fileCopy("C://Users/diyvc/Desktop/test.txt","C://Users/diyvc/Desktop/copy.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
相关文章推荐
- 将某盘的java文件复制到目标文件的方法。
- java文件复制最快的方法!
- 黑马程序员——java-使用IO流复制文件主要的五种方法
- Java: 复制文件最快方法
- 【Java】利用文件通道的方式改进Java复制单个文件的方法
- java 3中方法复制一个文件
- Java 复制文件的高效方法
- java中复制文件的新方法
- Java 实现文件复制方法
- FileChannel-Java 复制文件的高效方法
- 4 Ways to Copy File in Java -- Java 复制文件的方法
- Java: 复制文件最快方法
- Java: 复制文件最快方法
- Java: 复制文件最快、高效率的方法
- java写的一个用字节流复制文件的方法
- java 本地文件复制的方法
- java复制文件的简单方法
- Java中的4种文件复制方法
- Java IO学习【13】利用字节流复制文件的4种方法详解
- java: 复制文件最快方法