IO流的练习2 —— 复制单级文件夹中的文件

需求:把C:\Users\Administrator\Desktop\记录\测试里面的所有文件复制到
    C:\Users\Administrator\Desktop\新建文件夹\copy文件夹中
分析:
    A:封装目录
    B:获取该目录下的所有文件的File数组
    C:遍历该集合,得到每一个File对象
    D:把每个File复制到目的文件夹中

     public static void main(String[] args) throws IOException {
// 封装目录
File start = new File("C:\\Users\\Administrator\\Desktop\\记录\\测试");
File end = new File("C:\\Users\\Administrator\\Desktop\\新建文件夹\\copy");
//如果目的文件夹不存在,则创建
if(!end.exists()){
end.mkdir();
} //得到start目录下的所有文件的File数组
File[] f = start.listFiles();
//遍历数组,得到每一个file对象
for(File file : f){
//System.out.println(f);
//数据源——————C:\Users\Administrator\Desktop\记录\测试\Student.class 其中的一个
//System.out.println(f.getName());//Student.class
//目的地------C:\\Users\\Administrator\\Desktop\\新建文件夹\\copy\\Student.class //为了在目的文件夹中创建这样的文件,就得用拼接,把end和文件名拼接起来
String name = file.getName();
File newfile = new File(end,name);//File的第三种构造方法 //把数据源中文件的数据复制到目的文件中
copyfile(file,newfile);
} } private static void copyfile(File file, File newfile) throws IOException {
// 把file中的数据复制到newfile中,因为任何类型文件都复制,所以用缓冲字节流
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bo = new BufferedOutputStream (new FileOutputStream(newfile));
//读一个字节数组的方式:
byte[] by = new byte[1024];
int len = 0;
while((len = bi.read(by)) != -1){
bo.write(by,0,len);
}
bi.close();
bo.close();
}
上一篇:创建自定义的Middleware中间件


下一篇:hdu 3948(后缀数组+RMQ)