从内存到硬盘 读操作
从硬盘到内存 写操作
package com.file;
import java.io.*;
/**
* java实现复制,练习java中的IO知识点,掌握读写。
* 动力节点P748
* document
*
* 实现思路:
* 1.建立源文件
* 2,建立目标文件
* 3,调用复制方法
* 4,递归调用复制方法,找到文件目录下的所有文件,判断文件是否找到,如找到结束递归
* 5,定义目标路径,根据目标路径创建文件夹
* 6,创建IO流,根据流操作一边读一边写
* 7,从E盘读到内存,从内存写入F盘
* 8,定义byte数组读
* 9,循环写入
*
*/
public class CopyTest {
public static void main(String[] args) {
//源目标
File srcFile = new File("E:\\JavaSE\\code");
//目标
File destFile = new File("F:\\JAVA108\\compare");
//调用复制方法ttt
copy(srcFile,destFile);
}
public static void copy(File srcFile,File destFile){
//判断该路径是否是文件,是文件就返回,结束递归
if(srcFile.isFile()){ //判断是否是文件
//一边读一边写
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//读这个文件
fis = new FileInputStream(srcFile);
//写这个文件
String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath()+"\\") + srcFile.getAbsolutePath().substring(3);
fos = new FileOutputStream(path);
byte[] bytes = new byte[1024 * 1024];
int readCont = 0;
while ( (readCont = fis.read(bytes)) != -1){
fos.write(bytes,0,readCont);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fis != null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return;
}
File[] files = srcFile.listFiles();
for (File file : files) {
//System.out.println(file.getAbsolutePath());
if(file.isDirectory()){ //判断是否是文件夹
String srcdir = file.getAbsolutePath();
String destdir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath()+"\\") + srcdir.substring(3);
File newFile = new File(destdir);
if( !newFile.exists()){ // 判断文件夹是否存在
newFile.mkdirs(); //创建多级文件夹
}
}
//递归复制方法
copy(file,destFile);
}
}
}