Java文件操作方法

Java文件操作方法

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;

/**
 * 关于文件操作的工具类
 *
 */

public class FileUtil {
	
	private static Logger logger = Logger.getLogger(FileUtil.class);

	
	/**
	 * 创建目录,如果有多级目录,则遍历创建
	 * @param directory
	 */
	public static void mkdir(String directory) {
	    File file = new File(directory);
	    //如果目录存在不做任何处理
	    if(file.exists()) {
	      return;
	    }
	    try {
	      file.mkdirs();
	    }
	    catch (Exception e) {
	      throw new RuntimeException("创建目录["+directory+"]失败",e);
	    }    
	   
	  }
	
	/**
	 * 获取本地目录下所有文件夹
	 * @param path
	 * @return
	 */
	public static List<String> listLocalFileDirs(String path){
		List<String> fileNameList = new ArrayList<String>();
		File file=new File(path);
		File[] tempList = file.listFiles();
		if (tempList == null ) return null;
		for (int i = 0; i < tempList.length; i++) {
		   if (tempList[i].isDirectory()) 
			   fileNameList.add(tempList[i].getName());
		}
		return fileNameList;
	}
	
	/**
	 * 获取本地目录下所有文件和文件夹
	 * @param path
	 * @return
	 */
	public static List<String> listLocalFileAndDirs(String path){
		List<String> fileNameList = new ArrayList<String>();
		File file=new File(path);
		File[] tempList = file.listFiles();
		for (int i = 0; i < tempList.length; i++) {
		   if (tempList[i].isDirectory() || tempList[i].isFile()) 
			   fileNameList.add(tempList[i].getName());
		}
		return fileNameList;
	}
	
	/**
	 * 判断本地文件夹是否存在
	 * @param directory
	 * @return
	 */
	public static boolean isDirExist(String directory){
		File file = new File(directory);
	    
	    if(file.exists() && file.isDirectory())
	    	return true;
	    else
	    	return false;
	}
	
	/**
	 * 复制文件或文件夹里的所有内容到另一个文件夹
	 * @param fromPath
	 * @param toPath
	 */
	public static void copyFile(String fromPath, String toPath) {  
        File fromfile = new File(fromPath);  
        File toFile = new File(toPath);  
        try {  
            copy(fromfile, toFile);  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
  
    public static void copy(File file, File toFile) throws Exception {  
        byte[] b = new byte[1024];  
        int a;  
        FileInputStream fis;  
        FileOutputStream fos;  
        if (file.isDirectory()) {  
            String filepath = file.getAbsolutePath();  
            filepath=filepath.replaceAll("\\\\", "/");  
            String toFilepath = toFile.getAbsolutePath();  
            toFilepath=toFilepath.replaceAll("\\\\", "/");  
            int lastIndexOf = filepath.lastIndexOf("/");  
            toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());  
            File copy=new File(toFilepath);  
            //复制文件夹  
            if (!copy.exists()) {  
                copy.mkdir();  
            }  
            //遍历文件夹  
            for (File f : file.listFiles()) {  
                copy(f, copy);  
            }  
        } else {  
            if (toFile.isDirectory()) {  
                String filepath = file.getAbsolutePath();  
                filepath=filepath.replaceAll("\\\\", "/");  
                String toFilepath = toFile.getAbsolutePath();  
                toFilepath=toFilepath.replaceAll("\\\\", "/");  
                int lastIndexOf = filepath.lastIndexOf("/");  
                toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());  
                  
                //写文件  
                File newFile = new File(toFilepath);  
                fis = new FileInputStream(file);  
                fos = new FileOutputStream(newFile);  
                while ((a = fis.read(b)) != -1) {  
                    fos.write(b, 0, a);  
                }  
                fis.close();
                fos.close();
            } else {  
                //写文件  
                fis = new FileInputStream(file);  
                fos = new FileOutputStream(toFile);  
                while ((a = fis.read(b)) != -1) {  
                    fos.write(b, 0, a);  
                }  
                fis.close();
                fos.close();
                
            }  
  
        }  
        
        
    }  
    
    /**
     * 重命名文件夹
     * @param path
     * @param oldname
     * @param newname
     */
    public static boolean renameFile(String path,String oldname,String newname){ 
        if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名 
            File oldfile=new File(path+"/"+oldname); 
            File newfile=new File(path+"/"+newname); 
            if(!oldfile.exists()){
                return false;//重命名文件不存在
            }
            if(!newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名 

               return oldfile.renameTo(newfile); 
            
    	}
        return false;
    }
    
    /**
     * 删除文件夹
     * @param path
     */
    public static boolean deleteAllFilesOfDir(String dir) {  
    	File path = new File(dir);  
        if (!path.exists())  
            return false;  
        if (path.isFile()) {  
            path.delete();  
            return false;  
        }  
        File[] files = path.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            deleteAllFilesOfDir(files[i].getPath());  
        }  
        path.delete();  
        return true;  
    }  
    
    /**
     * 删除空文件夹
     * @param path
     */
    public static boolean deleteNullDir(String dir) {  
    	File path = new File(dir);  
        if (!path.exists())  
            return false;  
        if (path.isDirectory() && path.listFiles().length <= 0) {  
            path.delete();  
            return true;
        }  
        File[] files = path.listFiles();  
        for (int i = 0; i < files.length; i++) {  
        	if (files[i].isDirectory())
        		deleteNullDir(files[i].getPath());  
        }  
        return true;  
    }  
}


猜你喜欢

转载自blog.csdn.net/u010469514/article/details/78135726