欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java移动文件并编辑文件内容

程序员文章站 2022-07-09 20:18:08
...
package com.wonders.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
  
/**
 * 将文件夹下所有文件(包括子文件夹下的文件)复制到target下(同一层次)(并编辑文件)
 * @author Admin
 *
 */
public class DirErgodic {  
  
    private static int depth = 1;
    private static int size = 1; 
      
    /**
     * 将文件夹下所有文件(包括子文件夹下的文件)复制到target下(同一层次)
     * @param pathName
     * @param depth
     * @param target
     * @throws IOException
     */
    public static void find(String pathName,int depth,String target) throws IOException{  
        int filecount=0;  
        //获取pathName的File对象  
        
        File dirFile = new File(pathName);  
        //判断该文件或目录是否存在,不存在时在控制台输出提醒  
        if (!dirFile.exists()) {  
            System.out.println("do not exit");  
            return ;  
        }  
        File targetDir = new File(target);  
        //判断该文件或目录是否存在,不存在时在控制台输出提醒  
        if (!targetDir.exists()) {  
        	targetDir.mkdirs();
        }  
        //判断如果不是一个目录,就判断是不是一个文件,时文件则输出文件路径  
        if (!dirFile.isDirectory()) {  
            if (dirFile.isFile()) {  
                System.out.println(dirFile.getCanonicalFile());  
            }  
            return ;  
        }  
          
        for (int j = 0; j < depth; j++) {  
            System.out.print("  ");  
        }  
        System.out.print("|--");  
        System.out.println(dirFile.getName());  
        //获取此目录下的所有文件名与目录名  
        String[] fileList = dirFile.list();  
        int currentDepth=depth+1;  
        for (int i = 0; i < fileList.length; i++) {  
            //遍历文件目录  
            String string = fileList[i];  
            //File("documentName","fileName")是File的另一个构造器  
            File file = new File(dirFile.getPath(),string);  
            String name = file.getName();  
            //如果是一个目录,搜索深度depth++,输出目录名后,进行递归  
            if (file.isDirectory()) {  
                //递归  
                find(file.getCanonicalPath(),currentDepth,target);  
            }else{  
            	
//            	copyFile(file,new File(target+"\\"+name));
            	updateToNewHtmlFile(file,new File(target+"\\"+name));
                //如果是文件,则直接输出文件名  
                for (int j = 0; j < currentDepth; j++) {  
                    System.out.print("   ");  
                }  
                System.out.print("|--");  
                System.out.println(size+": "+name);  
                size++;  
            }  
        }  
    }  
    
    // 复制文件
    public static void copyFile(File sourceFile, File targetFile) throws IOException
    {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try 
        {
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); 
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            byte[] b = new byte[1024 * 5]; 
            int len;
            while ((len = inBuff.read(b)) != -1) 
            {
                outBuff.write(b, 0, len);
            }
            
            outBuff.flush();
        } 
        finally 
        {
            
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
    
    public static boolean updateToNewHtmlFile(File sourceFile, File targetFile) {
		String str = "";
		long beginDate = (new Date()).getTime();
		str = getValue(readfile(sourceFile));
		try {

			BufferedWriter o = new BufferedWriter(new FileWriter(targetFile));
			o.write(str);
			o.close();
			System.out.println("共用时:" + ((new Date()).getTime() - beginDate)
					+ "ms");
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
    
    public static String readfile(File file) {
    	//保存原格式
		InputStream input = null;
		try {
			input = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		StringBuffer buffer = new StringBuffer();
		byte[] bytes = new byte[1024];
		try {
			for (int n; (n = input.read(bytes)) != -1;) {
				buffer.append(new String(bytes, 0, n, "GBK"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
//输出文件为一行:踢出空行
//		StringBuffer buffer = new StringBuffer();
//		try {
//			String tempStr = "";
//			FileInputStream is = new FileInputStream(file);// 读取模块文件
//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
//			while ((tempStr = br.readLine()) != null)
//				buffer.append(tempStr);
//			is.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		
		
		return buffer.toString();
	}
    
    public static String getValue(String val) {
		String end = "</html>";
		int e = val.indexOf(end)+ end.length();
		return val.substring(0, e);
	}
      
    public static void main(String[] args) throws IOException{  
    	 // 开始时间
        Long begin = new Date().getTime();
        find("D:\\source\\annex", depth,"E:\\a");
        
        // 结束时间
        Long end = new Date().getTime();
        // 耗时
        System.out.println("花费时间 : " + (end - begin) / 1000 + " s"+"");
    }  
}