`

java文件操作

阅读更多
package com.basic;

import java.io.*;
import java.util.StringTokenizer;

/*
 * @author zhaozhi3758
 * @desc java文件基本操作
 */
public class FileT {
	/**
	 * 读取单个文本
	 * @param path 源路径
	 */
	public String readerFile(String path) {
		//long a=System.currentTimeMillis();  
		String str = "";
		try {
			FileReader ffield = new FileReader(path);
			BufferedReader fieldbuff = new BufferedReader(ffield);
			String fieldline = fieldbuff.readLine();
			while (fieldline != null) {
				str = str + fieldline + "\n";
				fieldline = fieldbuff.readLine();
			}
			fieldbuff.close();
			ffield.close();
		} catch (IOException e) {
			System.out.println("this file not exist " + path);
		}
		//long b=System.currentTimeMillis();
		//System.out.println(a-b);
		return str;

	}

	/**
	 * 读取单个文本[效率高些]
	 * @param path 源路径
	 */
	public String readerFile_B(String path) {
		//long a=System.currentTimeMillis();  
		StringBuffer sb = new StringBuffer();
		try {
			FileReader ffield = new FileReader(path);
			BufferedReader fieldbuff = new BufferedReader(ffield);
			String fieldline = "";
			while ((fieldline = fieldbuff.readLine()) != null) {
				sb.append(fieldline);
				sb.append("\n");
			
			}
			fieldbuff.close();
			ffield.close();
		} catch (IOException e) {
			System.out.println("this file not exist " + path);
		}
		//long b=System.currentTimeMillis();
		//System.out.println(a-b);
		return sb.toString();

	}

       //--由路径读取文件
	   static public String LoadFile(String strFileName){
		    StringBuffer sb = new StringBuffer();   
	        try {   
	        	   BufferedReader fieldbuff = new BufferedReader(new InputStreamReader(
	        			   new FileInputStream(strFileName),"utf-8")); 
	        	//FileReader ffield = new FileReader(strFileName);   
	            //BufferedReader fieldbuff = new BufferedReader(ffield);   
	            String fieldline = "";   
	            while ((fieldline = fieldbuff.readLine()) != null) {   
	                sb.append(fieldline);   
	                sb.append("\n");   
	               
	            }   
	            fieldbuff.close();   
	           // ffield.close();   
	        } catch (IOException e) {   
	            System.out.println("this file not exist " + strFileName);   
	        }   
	        return sb.toString();   

	    }



	/*写入文件
	 * @param path file address
	 * @param str String
	 * @throws IOException 
	 */
	public void writrToFile(String path,String str) throws FileNotFoundException{
		PrintWriter pw = new PrintWriter(new FileOutputStream(path));
        pw.println(str);
        pw.flush();
        pw.close();
		
	}

/**
		 * 上传文件
		 * 
		 * @param uploadFileName
		 *          被上传的文件名称
		 * @param savePath
		 *          文件的保存路径
		 * @param uploadFile
		 *          被上传的文件
		 * @return newFileName
		 */
		public static void upload(String uploadFileName, String savePath, File uploadFile) {
			try {
				FileOutputStream fos = new FileOutputStream(savePath + uploadFileName);
				FileInputStream fis = new FileInputStream(uploadFile);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				fos.close();
				fis.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		

	   static  public void SaveToFile(String strbody,String strFileName){
	        try {
	           
	            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(strFileName),"UTF-8");
	            BufferedWriter writer=new BufferedWriter(write);  
	           
	            writer.write(strbody);
	            writer.close();
	            
	        } catch(IOException e) {
	            System.out.println("写入文件失败!"+strFileName);
	            e.printStackTrace();
	        }
	    }

	/**
	 * 新建一级目录
	 * @param folderPath 目录
	 */
	public void createFolder(String folderPath) {
		File myFilePath = new File(folderPath);
		if (!myFilePath.exists()) {
			myFilePath.mkdir();
		}

	}
	/**
	 * 新建多级目录[1]
	 * @param folderPath 目录
	 */
	public void createFolders(String folderPath) {
		   StringTokenizer   st=new StringTokenizer(folderPath,"/");   
	       String path1=st.nextToken()+"/";   
	       String path2 =path1;
	       while(st.hasMoreTokens()){   
	             path1=st.nextToken()+"/";  
	             path2+=path1; 
	             File inbox =new File(path2);   
	             if(!inbox.exists())   
	             inbox.mkdir();   
	       }


	}
	//新建多级目录[2]
	public void makeDir(String absPath){
		File folder = new File(absPath);
		if(!folder.exists()){
			folder.mkdirs();
		}
	}

	/*以文件流的方式复制单个文件,支持中文以及多种格式 
	 * @param src 文件源目录 
	 * @param dest 文件目的目录 
	 * @throws IOException 
	 */
	public void copyFile(String src, String dest) throws IOException {
		FileInputStream in = new FileInputStream(src);
		/*File file=new File(dest); 
		if(!file.exists()) 
		file.createNewFile(); */
		String folder = dest.substring(0, dest.lastIndexOf("/"));
		//System.out.println(folder);
		createFolder(folder);
		FileOutputStream out = new FileOutputStream(dest);//默认会自动创建文件,但不会自动创建文件夹 
		int c;
		byte buffer[] = new byte[1024];
		while ((c = in.read(buffer)) != -1) {
			for (int i = 0; i < c; i++)
				out.write(buffer[i]);
		}
		in.close();
		out.close();
	}

	/**
	 * 复制整个文件夹的内容
	 * @param oldPath 准备拷贝的目录
	 * @param newPath 指定绝对路径的新目录
	 */

	public void copyFolder(String oldPath, String newPath) throws IOException {
		createFolder(newPath); //如果文件夹不存在 则建立新文件夹
		File a = new File(oldPath);
		String[] file = a.list();
		File temp = null;
		for (int i = 0; i < file.length; i++) {
			//System.out.println(file[i]);//文件名 b.doc或者文件目录名temp
			if (oldPath.endsWith(File.separator)) {//与系统有关的默认名称分隔符
				temp = new File(oldPath + file[i]);
			} else {
				temp = new File(oldPath + File.separator + file[i]);
			}

			if (temp.isFile()) {
				FileInputStream input = new FileInputStream(temp);
				FileOutputStream output = new FileOutputStream(newPath + "/"
						+ temp.getName());
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = input.read(b)) != -1) {
					output.write(b, 0, len);//将指定 byte 数组中从偏移量 0 开始的 len 个字节写入此文件输出流
				}
				output.flush();
				output.close();
				input.close();
			}
			if (temp.isDirectory()) {//如果是子文件夹
				copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);

			}
		}
	}

	/**
	 * 删除单个文件或文件夹
	 * @param filePathAndName 文本文件完整绝对路径及文件名
	 */
	public void delFile(String filePath) {
		File myDelFile = new File(filePath);
		if (myDelFile.exists()) {
			myDelFile.delete();
		}
	}

	/**
	 * 删除多个文件[若有文件夹,则文件夹及里面的内容是删不掉的]
	 * @param filePath 文本文件完整绝对路径及文件名
	 */
	public void delFiles(String filePath) {
		File folder = new File(filePath);
		if (folder.isDirectory()) {//is directory   
			File[] fileList = folder.listFiles();
			for (File file : fileList) {
				if (file.isFile()) {
					file.delete();
				}
			}
		}

	}

	/**
	 * 删除文件夹[必须先删除里面的内容]
	 * @param folderPath 文件夹完整绝对路径
	 */

	public void delFolder(String filePath) throws IOException {
		delAllFile(filePath); //删除完里面所有内容
		File myFilePath = new File(filePath);
		myFilePath.delete(); //删除空文件夹
	}

	/**
	 * 删除指定文件夹下所有文件[根文件夹没有删除]
	 * @param path 文件夹完整绝对路径
	 */
	public void delAllFile(String path) throws IOException {
		File file = new File(path);
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);//再删除空文件夹
			}
		}
	}
	//列出文件地址
	public void listFile(String filePath){//列出一级
	    File folder = new File(filePath);
		File[] fileList = folder.listFiles();
		for(File file:fileList){//f:\凌天传说.txt[带有根路径]
			System.out.println(file);
			System.out.println(file.getAbsolutePath());//f:\凌天传说.txt
			System.out.println(file.getName());//凌天传说.txt
			
		}
		System.out.println("-----------");
		String f[]=folder.list();
		for(String file:f){//凌天传说.txt
			System.out.println(file);
		}
		//file.listRoots() 
	
	
}
    //重命名文件夹或者文件
    public void reNameFile(String path,String oldFile,String newFile){
		File of=new File(path+"/"+oldFile);
		File nf=new File(path+"/"+newFile);
		if(of.exists()){
			if(of.isDirectory()){
				System.out.println("重命名文件夹开始....");
				of.renameTo(nf);
			    System.out.println("重命名文件夹结束....");
			
			}
			if(of.isFile()){
				System.out.println("重命名文件开始....");
				of.renameTo(nf);
			    System.out.println("重命名文件结束....");
			}
			
		}
		
}

   //对于移动某个文件夹设计思想是:先复制,再删除
	public static void main(String[] args) throws IOException {
		FileT f = new FileT();
		//f.copyFile("f:/file/a.xls","f:/file/temp/b.xls");
		//f.copyFolder("f:/file/", "f:/test");
		//f.delFolder("f:/test");
		//f.delAllFile("f:/test");
		//f.delFiles("f:/test");
		//System.out.println(f.readerFile_B("f:/file/a.txt"));
		//f.makeDir("f:/com/trade/info");
		//f.writrToFile("f:/com/trade/info/a.java","  drger\ngerghr");
		 //f.listFile("f:/");
		f.reNameFile("f:/com/trade/voteoption/", "VoteoptionInfo.java", "trade.java");

	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics