自己写的剪切文件代码

来源:互联网 发布:华软市政软件 编辑:程序博客网 时间:2024/04/29 13:02
package com.itcast;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;/* * 剪切一个非空文件夹 */public class Prac1 {public static void main(String[] args) throws IOException {File srcFile = new File("F:\\aa");File destFile = new File("E:\\aa");pasteFile(srcFile,destFile);}private static void pasteFile(File srcFile, File destFile) throws IOException {// TODO Auto-generated method stubFile[] files = srcFile.listFiles();for (File file : files) {if (file.isFile()) {copyFile(file,destFile);deleteFile(file);}else{//递归,遍历文件夹pasteFile(new File(srcFile,file.getName()), new File(destFile,file.getName()));}srcFile.delete();}}private static void deleteFile(File srcFile) {// TODO Auto-generated method stubsrcFile.delete();}//复制文件private static void copyFile(File srcFile, File destFile) throws IOException{//判断文件夹是否存在if (!destFile.exists()) {new File(destFile.getAbsolutePath()).mkdir();}//使用字节流读取文件BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFile));File newFile = new File(destFile,srcFile.getName());//写入文件BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(newFile));//定义一个缓冲数组byte[] buf = new byte[1024];int len = 0;while ((len = bufferedInputStream.read(buf))!=-1) {bufferedOutputStream.write(buf, 0, len);}//关闭资源。bufferedOutputStream.close();bufferedInputStream.close();}}
代码的所有IO异常都抛出去了,不是很好哈~
0 0
原创粉丝点击