`
uyerp
  • 浏览: 11645 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

文件操作

阅读更多
package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.StringTokenizer;

public class FileUtil {

	/**
	 * 读取文本文件内容
	 * 
	 * @param filePathAndName
	 *            带有完整绝对路径的文件名
	 * @param encoding
	 *            文本文件打开的编码方式
	 * @return 返回文本文件的内容
	 */
	public static String readTxt(String filePathAndName, String encoding)
			throws IOException {
		encoding = encoding.trim();
		StringBuffer str = new StringBuffer("");
		String st = "";
		try {
			FileInputStream fs = new FileInputStream(filePathAndName);
			InputStreamReader isr;
			if (encoding.equals("")) {
				isr = new InputStreamReader(fs);
			} else {
				isr = new InputStreamReader(fs, encoding);
			}
			BufferedReader br = new BufferedReader(isr);
			try {
				String data = "";
				while ((data = br.readLine()) != null) {
					str.append(data + "\r\n");
				}
			} catch (IOException e) {
				str.append(e.toString());
			}
			st = str.toString();
		} catch (IOException es) {
			throw es;
		}
		return st;
	}

	/**
	 * 新建文件
	 * 
	 * @param filePathAndName
	 *            文本文件完整绝对路径及文件名
	 * @param fileContent
	 *            文本文件内容
	 * @return
	 * @throws Exception
	 */
	public static void createFile(String filePathAndName, String fileContent)
			throws Exception {

		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			FileWriter resultFile = new FileWriter(myFilePath);
			PrintWriter myFile = new PrintWriter(resultFile);
			String strContent = fileContent;
			myFile.println(strContent);
			myFile.close();
			resultFile.close();
		} catch (Exception e) {
			throw new Exception("创建文件操作出错", e);
		}
	}

	/**
	 * 有编码方式的文件创建
	 * 
	 * @param filePathAndName
	 *            文本文件完整绝对路径及文件名
	 * @param fileContent
	 *            文本文件内容
	 * @param encoding
	 *            编码方式 例如 GBK 或者 UTF-8
	 * @return
	 * @throws Exception
	 */
	public static void createFile(String filePathAndName, String fileContent,
			String encoding) throws Exception {

		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			PrintWriter myFile = new PrintWriter(myFilePath, encoding);
			String strContent = fileContent;
			myFile.println(strContent);
			myFile.close();
		} catch (Exception e) {
			throw new Exception("创建文件操作出错", e);
		}
	}

	/**
	 * 创建文件夹
	 * 
	 * @param filePath
	 * @throws Exception
	 */
	public static String createFolder(String filePath) throws Exception {
		File file = new java.io.File(filePath);
		try {
			if (!file.exists()) {
				if (!file.mkdir()) {
					throw new IOException("创建文件夹:" + filePath + "出错");
				}
			}
			return filePath;
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 多级目录创建
	 * 
	 * @param folderPath
	 *            准备要在本级目录下创建新目录的目录路径 例如 E:\\Test\\java\\
	 * @param paths
	 *            无限级目录参数,各级目录以单数线区分 例如 a|b|c
	 * @return 返回创建文件夹后的路径 例如 c:myfa c
	 * @throws Exception
	 */
	public static String createFolders(String folderPath, String paths)
			throws Exception {
		String txts = folderPath;
		try {
			String txt;
			txts = folderPath;
			StringTokenizer st = new StringTokenizer(paths, "|");
			for (int i = 0; st.hasMoreTokens(); i++) {
				txt = st.nextToken().trim();
				txts = createFolder(txts + txt + "/");
			}
		} catch (Exception e) {
			throw new Exception("创建目录操作出错!", e);
		}
		return txts;
	}

	/**
	 * 复制单个文件
	 * 
	 * @param oldPathFile
	 *            准备复制的文件源
	 * @param newPathFile
	 *            拷贝到新绝对路径带文件名
	 * @return
	 * @throws Exception
	 */
	public static void copyFile(String oldPathFile, String newPathFile)
			throws Exception {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPathFile);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPathFile);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * <p>
	 * 将sourceFolder文件夹下的内容复制到destinationFolder文件夹下
	 * </p>
	 * <p>
	 * 如destinationFolder文件夹不存在则自动创建
	 * </p>
	 * 
	 * @param sourceFolder
	 *            源文件夹 如:C:\\aaa
	 * @param destinationFolder
	 *            目标文件夹 D:\\java
	 * @throws Exception
	 */
	public static void copyFolder(String sourceFolder, String destinationFolder)
			throws Exception {
		try {
			new File(destinationFolder).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(sourceFolder);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (sourceFolder.endsWith(File.separator)) {
					temp = new File(sourceFolder + file[i]);
				} else {
					temp = new File(sourceFolder + File.separator + file[i]);
				}
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(
							destinationFolder + "/"
									+ (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(sourceFolder + "/" + file[i], destinationFolder
							+ "/" + file[i]);
				}
			}
		} catch (Exception e) {
			throw new Exception("复制整个文件夹内容操作出错", e);
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param filePathAndName
	 *            文本文件完整绝对路径及文件名
	 * @return Boolean 成功删除返回true遭遇异常返回false
	 */
	public static void delFile(String filePathAndName) throws Exception {
		try {
			String filePath = filePathAndName;
			File myDelFile = new File(filePath);
			if (myDelFile.exists()) {
				myDelFile.delete();
			} else {
				throw new IOException(filePathAndName + "删除文件操作出错");
			}
		} catch (IOException e) {
			throw new Exception(filePathAndName + "删除文件操作出错", e);
		}
	}

	/**
	 * 删除文件夹
	 * 
	 * @param folderPath
	 *            文件夹完整绝对路径
	 * @return
	 * @throws Exception
	 */
	public static void delFolder(String folderPath) throws Exception {

		try {
			delAllFile(folderPath);
			// 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			boolean result = myFilePath.delete(); // 删除空文件夹
			if (!result) {
				throw new IOException("文件夹:" + folderPath + ",删除失败");
			}
		} catch (IOException e) {
			throw new Exception("删除文件夹出错", e);
		}
	}

	/**
	 * 删除文件及文件夹下所有文件
	 * 
	 * @return
	 * @throws IOException
	 */
	public static boolean delAllFile(String filePath) throws IOException {
		File file = new File(filePath);
		if (!file.exists())// 文件夹不存在不存在
			throw new IOException("指定目录不存在:" + file.getName());
		boolean rslt = true;// 保存中间结果
		if (!(rslt = file.delete())) {// 先尝试直接删除
			// 若文件夹非空。枚举、递归删除里面内容
			File subs[] = file.listFiles();
			for (int i = 0; i <= subs.length - 1; i++) {
				if (subs[i].isDirectory())
					delAllFile(subs[i].toString());// 递归删除子文件夹内容
				rslt = subs[i].delete();// 删除子文件夹本身
			}
			// rslt = file.delete();// 删除此文件夹本身
		}

		if (!rslt)
			throw new IOException("无法删除:" + file.getName());
		// 删除文件
		return true;
	}

	/**
	 * 移动文件
	 * 
	 * @param oldPath
	 * @param newPath
	 * @return
	 * @throws Exception
	 */
	public static void moveFile(String oldPath, String newPath)
			throws Exception {

		try {
			copyFile(oldPath, newPath);
			delFile(oldPath);
		} catch (Exception e) {
			throw e;
		}

	}

	/**
	 * 移动目录
	 * 
	 * @param oldPath
	 * @param newPath
	 * @return
	 */
	public static void moveFolder(String oldPath, String newPath) {
		try {
			copyFolder(oldPath, newPath);
			delFolder(oldPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * <p>
	 * 取得当前类文件所在绝对路径
	 * </p>
	 * <p>
	 * 如:E:/workspace/mobile/WebRoot/WEB-INF/classes/com/mobileSky/ty/utils/
	 * </p>
	 * 
	 * @return
	 */
	public static String getClassPath() {
		String strClassName = FileUtil.class.getName();

		String strPackageName = "";
		if (FileUtil.class.getPackage() != null) {
			strPackageName = FileUtil.class.getPackage().getName();
		}

		String strClassFileName = "";
		if (!"".equals(strPackageName)) {
			strClassFileName = strClassName.substring(
					strPackageName.length() + 1, strClassName.length());
		} else {
			strClassFileName = strClassName;
		}

		URL url = null;
		url = FileUtil.class.getResource(strClassFileName + ".class");
		String strURL = url.toString();
		strURL = strURL.substring(strURL.indexOf('/') + 1, strURL
				.lastIndexOf('/'));
		return strURL + "/";
	}

	/**
	 * 取得当前项目根目录,如:E:/workspace/mobile/,其中mobile为项目名
	 * 
	 * @param projectName
	 * @return
	 */
	public static String getProject(String projectName) {
		String classPath = getClassPath();
		return classPath.substring(0, classPath.indexOf(projectName)
				+ projectName.length() + 1);
	}

	/**
	 * 将C:\aaa\dsa转换为C:/aaa/dsa
	 * 
	 * @param path
	 * @return
	 */
	public static String getStr(String path) {
		String result = "";
		char[] pathChar = path.toCharArray();
		for (int i = 0; i < pathChar.length; i++) {
			if (pathChar[i] == '\\') {
				pathChar[i] = '/';
			}
			result += pathChar[i];
		}
		return result;
	}

	public static void main(String arg[]) {

		try {
			copyFolder("E:\\百度网页\\百度指数搜索_java.files", "E:\\百度网页\\重新生产\\百度指数搜索_java.files");
			//moveFolder("E:\\百度网页\\百度指数搜索_java.files","E:\\百度网页\\xxx\\百度指数搜索_java.files");
			// delAllFile("E:\\Test\\java");
			// delFolder("E:\\Test\\java");
			// createFile("E:\\Test\\java\\a.xml",
			// "<abc>\r\n<a>\r\n</a>\r\n</abc>");
			// createFolder("E:\\Test\\java");
			// createFolders("E:\\Test\\java\\", "一级|二级|三级");
			//String a = readTxt("E:\\Test\\java\\a.xml", "GBK");
			//System.out.println(a);
		} catch (Exception e) {
			e.printStackTrace();
		} 

	}
}
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    模拟实现采用二级目录结构的磁盘文件系统中的文件操作。

    模拟实现采用二级目录结构的磁盘文件系统中的文件操作。 文件系统是操作系统中管理和存取信息的机构,它具有“按名存取”的功能,不仅方便用户,而且能提高系统效率且安全可靠。 在用户程序中可使用文件系统提供的...

    读写文件读取文件操作读取文件操作读取文件操作读取文件操作

    读取文件操作读取文件操作读取文件操作读取文件操作读取文件操作读取文件操作读取文件操作读取文件操作读取文件操作读取文件操作读取文件操作

    C++文件操作 C++ 文件操作

    很详细的C++文件操作 C++ 通过以下几个类支持文件的输入输出: ofstream: 写操作(输出)的文件类 (由ostream引申而来) ifstream: 读操作(输入)的文件类(由istream引申而来) fstream: 可同时读写操作的文件类 ...

    linux文件操作 linux操作系统 文件操作 常用命令

    linux文件操作 linux操作系统 文件操作 常用命令 系统命令

    C++ 文件操作大全

    C++ 文件操作大全,里面列举了几乎所有的C++文件操作以及相关细节。

    MFC文件操作详解

    MFC文件操作各种关于文件的操作在程序设计中是十分常见,如果能对其各种操作都了如指掌,就可以根据实际情况找到最佳的解决方案,从而在较短的时间内编写出高效的代码,因而熟练的掌握文件操作是十分重要的。...

    电子科技大学linux环境编程作业2——李林——编写带缓存的文件操作类

    编写带缓存的文件操作类 从执行体程序库中的CLLogger类可知,通过缓存要写入文件中的数据,能够提高读写磁盘的性能 请编写一个文件操作的封装类,其要求如下: 需要提供open/read/write/lseek/close等函数的封装函数...

    c#文件操作方法大全

    c#对文件或者文件夹全面的操作。以及c#对文件操作方面的一些属性的概述。

    python文件操作实验报告.doc

    python文件操作

    js对本地文件操作

    js对本地文件操作,仅限IE浏览器使用,其它浏览器不兼容(ActiveXObject方法)

    codesys工程ST语言写文件操作 TXT文件。

    本工程笔者使用ST语言实现文件的写操作,详细见本人博客,内容笔者亲测有效。后续更新读文件操作

    C语言的文件操作 C语言文件操作

    C语言文件操作 C语言文件操作 C语言文件操作

    Python文件操作(课件)

    详细介绍Python中的文件操作,包括文件操作的各种模式分析、文件夹的递归访问、Excel文件的读取和写入等,并通过具体示例演示说明,非常适合高校老师教学和学生复习使用。

    C语言文件操作及函数大全

    C语言文件操作及函数大全 2.文件操作函数: (1)文件打开函数fopen fopen函数用来打开一个文件,其调用的一般形式为: 文件指针名=fopen("文件名","使用文件方式"); 其中,“文件指针名”必须是被说明为FILE 类型的...

    文件操作函数大全文件操作函数大全

    文件操作函数大全文件操作函数大全文件操作函数大全文件操作函数大全文件操作函数大全文件操作函数大全文件操作函数大全文件操作函数大全

    21个文件操作VC 源码实例.rar

    收集了21个文件操作VC 源码实例,基础级别的VC 文件操作实例,获得INI文件指定段的全部键名和键值、文件对话框、临时文件创建、目录创建、获得INI文件的全部段名、查找文件、复制文件、获得或设置进程的当前目录、...

    C语言文件操作(文件操作)

    C语言文件操作(文件操作) FILE *p 那些的文件操作 我经常做些大型系统需要很多文件操作

    winform作的文件操作学习程序

    用winform作的文件操作程序,适合初学者入门学习,主要功能有:创建文件,删除文件,复制文件等等以及目录操作,文件的写入,读取,还有二进制文件的操作

    java文件操作类

    java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java...

    C++流类体系与文件操作

    通过本章学习,应理解I/O流、流类与流类体系的概念,...了解C++有关文件的概念及文件的使用方法,理解文件流类体系结构,掌握实现文件操作的成员函数的使用方法,学会文本文件的打开、读/写、关闭等操作的编程方法。

Global site tag (gtag.js) - Google Analytics