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

自定义文件读写工具类

程序员文章站 2022-04-28 12:43:09
...

public class FileUtil {

	/**
	 * 获得项目的物理路径(最后一个字符是分隔符).
	 * 
	 * @return
	 * @author sunny
	 * @create 2007-10-25 下午03:44:40
	 */
	public static String getAbsPathOfProject() {
		String url = FileUtil.class.getClassLoader().getResource("").toString();
		// Win file:/E:/projects/Eclipse/workspace/SAS-Studio/WEB-INF/classes/
		// Linux file:/home/share/SAS-TOMCAT/webapps/SAS/WEB-INF/classes/
		String reg = "file:(.+)WEB-INF";
		Matcher mat = Pattern.compile(reg, Pattern.CASE_INSENSITIVE).matcher(url);
		if (mat.find()) {
			String path = mat.group(1);
			path = path.replaceAll("/", "\\" + File.separator);
			return File.separator.equals("\\") ? path.substring(1) : path;
		}
		return url;
	}

	/**
	 * 文件类型 1:视频 2:音频 3:图片 4:其他
	 * 
	 * @param postfix
	 * @return
	 */
	public static int getFileType(String postfix) {
		Pattern p = Pattern.compile(Globals.VOD_POSTFIX);
		Matcher m = p.matcher(postfix);
		if (m.find())
			return 1;

		p = Pattern.compile(Globals.MP3_POSTFIX);
		m = p.matcher(postfix);
		if (m.find())
			return 2;

		p = Pattern.compile(Globals.PIC_POSTFIX);
		m = p.matcher(postfix);
		if (m.find())
			return 3;

		return 4;
	}

	/**
	 * 获取文件名后缀(.jpg)
	 * 
	 * @param fileName
	 * @return
	 * @author lihuan
	 * @create 2011-8-3 上午10:34:37
	 */
	public static String getPostFix(String fileName) {
		if (fileName == null || fileName.length() == 0)
			return "";
		int postFixIndex = fileName.lastIndexOf(".");
		if (postFixIndex != -1)
			return fileName.subSequence(postFixIndex, fileName.length()).toString().toLowerCase();
		else
			return "";
	}

	/**
	 * 获取文件名
	 * 
	 * @param fileName
	 * @return
	 * @author lihuan
	 * @create 2011-6-20 下午05:45:55
	 */
	public static String getName(String fileName) {

		if (fileName == null || fileName.length() == 0)
			return "";
		int postFixIndex = fileName.lastIndexOf(".");
		return fileName.subSequence(0, postFixIndex).toString();
	}

	/**
	 * 获取文件名
	 * 
	 * @param filePath
	 * @return
	 * @author lihuan
	 * @create 2012-5-18 下午03:47:35
	 */
	public static String getFileName(String filePath) {
		if (filePath == null || filePath.length() == 0)
			return "";
		int index = filePath.lastIndexOf("/");
		return filePath.subSequence(index + 1, filePath.length()).toString().toLowerCase();
	}

	/**
	 * 创建文件夹
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 * @author sunny
	 * @create 2007-10-25 下午03:07:18
	 */
	public synchronized static File mkDir(String filePath) throws Exception {
		File file = new File(filePath);
		if (!file.exists())
			file.mkdirs();
		return file;
	}

	/**
	 * 删除文件夹
	 * 
	 * @author Link Wang
	 * @create 2007-9-6 上午09:57:24
	 * @since
	 * @param dirPath
	 * @throws Exception
	 */
	public synchronized static boolean rmDir(String dirPath) {
		try {
			FileUtils.deleteDirectory(new File(dirPath));
			return true;
		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * 将二进制写入文件中.
	 * 
	 * @param file
	 * @param byt
	 * @return
	 * @author sunny
	 * @create 2007-2-2 下午03:57:13
	 */
	public static boolean writeByteToFile(File file, byte[] byt) {
		try {
			FileUtil.createFileBaseDir(file.getAbsolutePath());
			FileOutputStream out = new FileOutputStream(file);
			try {
				out.write(byt);
				out.flush();
				return true;
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 将二进制数据写如到文本文件中,可以指定文件编码
	 * 
	 * @param file
	 * @param bytes
	 * @return
	 * @author liangda
	 * @create 2010-10-28 上午09:57:13
	 */
	public static boolean writeTextWithEncoding(File file, byte[] bytes, String encoding) {
		try {
			FileUtil.createFileBaseDir(file.getAbsolutePath());
			InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(bytes));
			OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file), encoding);
			try {
				int lenth = 0;
				char[] buf = new char[1024];
				while ((lenth = in.read(buf, 0, 1024)) != -1) {
					os.write(buf, 0, lenth);
				}
				return true;
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (os != null)
					os.close();
				if (in != null)
					in.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 根据文件的路径,创建相关的文件夹
	 * 
	 * @author kongxiangpeng
	 * @create 2008-9-10 上午11:08:10
	 * @since
	 * @param filePath
	 */
	public static void createFileBaseDir(String filePath) {
		filePath = filePath.replace("/".charAt(0), File.separator.charAt(0));
		filePath = filePath.replace("\\".charAt(0), File.separator.charAt(0));

		File file = new File(filePath.substring(0, filePath.lastIndexOf(File.separator)));
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	/**
	 * 拷贝文件并改名
	 * 
	 * @param oldPath
	 * @param newPath
	 * @param newName
	 * @return
	 */
	public static boolean copyFileByPath(String oldPath, String newPath, String newName) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);

			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				File file = new File(newPath);
				if (!file.exists()) {
					file.mkdirs();
				}
				FileOutputStream fs = new FileOutputStream(newPath + File.separator + newName);
				byte[] buffer = new byte[1024];
				try {
					while ((byteread = inStream.read(buffer)) != -1) {
						bytesum += byteread; // 字节数 文件大小
						fs.write(buffer, 0, byteread);
					}
					fs.flush();
				} finally {
					fs.close();
					inStream.close();
				}
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 将二进制写入文件
	 * 
	 * @param absPath
	 *            绝对路径(包括文件名)
	 * @param byt
	 * @return
	 * @author sunny
	 * @create 2007-10-30 上午09:45:20
	 */
	public static boolean writeByteToFile(String absPath, byte[] byt) {
		String tmpPath = absPath.replace("\\".charAt(0), File.separator.charAt(0));
		String realPath = tmpPath.replace("/".charAt(0), File.separator.charAt(0));
		String fileFolder = realPath.substring(0, realPath.lastIndexOf(File.separator));
		File folder = new File(fileFolder);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		File file = new File(realPath);
		try {
			return writeByteToFile(file, byt);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return false;
	}

	/**
	 * 拷贝文件夹
	 * 
	 * @param oldPath
	 * @param newPath
	 */
	public static void copyFolder(String oldPath, String newPath) {

		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			if (file == null || file.length == 0)
				return;
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				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()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					try {
						while ((len = input.read(b)) != -1) {
							output.write(b, 0, len);
						}
						output.flush();
					} finally {
						output.close();
						input.close();
					}
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取class的绝对路径
	 * 
	 * @author kongxiangpeng
	 * @create 2008-9-17 下午12:19:16
	 * @since
	 * @return
	 */
	public static String getClassAbsPath() {
		return FileUtil.class.getClassLoader().getResource("").getPath();
	}

	/**
	 * 获得文件的扩展名(.txt)
	 * 
	 * @param fileName
	 * @return
	 * @author sunny
	 * @create 2007-5-31 上午09:56:23
	 */
	public static String getExtension(String fileName) {
		if (fileName == null)
			return null;
		String tmp = fileName.substring(fileName.lastIndexOf("."));
		return tmp;
	}

	/**
	 * 读文件,取得其字节数组
	 * 
	 * @author Link Wang
	 * @create 2007-9-26 上午11:51:09
	 * @since
	 * @param file
	 * @return
	 */
	public static byte[] readFileByte(File file) {
		try {
			return FileUtils.readFileToByteArray(file);
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 删除目录(文件夹)以及目录下的文件
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true,否则返回false
	 */
	public static boolean deleteDirectory(String sPath) {
		boolean flag = false;
		// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	/**
	 * 根据路径创建文件,或者空的文件夹
	 * 
	 * @param path
	 * @param flag
	 * @return
	 * @throws Exception
	 */
	public static File buildFile(String path, boolean flag) throws Exception {
		path = path.replace("/".charAt(0), File.separator.charAt(0));
		path = path.replace("\\".charAt(0), File.separator.charAt(0));
		if (!flag) {
			File file = new File(path);
			if (!file.exists()) {
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				file.createNewFile();
			}
			return file;
		} else {
			mkDir(path);
			return null;
		}
	}

	/**
	 * 读取文件夹下的所有文件的文件名称
	 * 
	 * @param filepath
	 * @param fileNams
	 * @return
	 */
	public static boolean readfile(String filepath, List<String> fileNams) {
		File file = new File(filepath);
		if (!file.exists()) {
			System.out.println("file not exists!");
			return false;
		}
		if (!file.isDirectory()) {
			System.out.println("file is not isDirectory!");
			fileNams.add(file.getName());
		} else if (file.isDirectory()) {
			System.out.println("file is  isDirectory!");
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readFile = new File(filepath + File.separator + filelist[i]);
				if (!readFile.isDirectory()) {
					System.out.println(readFile.getName());
					fileNams.add(readFile.getName());
				} else {
					readfile(filepath + File.separator + filelist[i], fileNams);
				}
			}
		}
		return true;
	}

	/**
	 * 获取当前目录下的文件夹
	 * 
	 * @param filepath
	 * @param fileNames
	 * @return
	 */
	public static boolean readDir(String filepath, List<String> fileNames) {
		File file = new File(filepath);
		if (file.isDirectory()) {
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readFile = new File(filepath + File.separator + filelist[i]);
				if (readFile.isDirectory()) {
					fileNames.add(readFile.getName());
				}
			}
		}
		return true;
	}

	/**
	 * 获取目录下制定后缀名的文件名称
	 * 
	 * @param filepath
	 *            目录
	 * @param fileType
	 *            后缀
	 * @return
	 */
	public static List<String> readDirFileByFix(String filepath, String fileType) {
		if (fileType == null || "".equals(fileType)) {
			return null;
		}
		fileType = fileType.toUpperCase();
		List<String> list = new ArrayList<String>();
		File file = new File(filepath);
		if (file.isDirectory()) {
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				String fileName = filelist[i];
				String type = getPostFix(fileName);
				if (type != null && type.toUpperCase().equals(fileType)) {
					list.add(fileName);
				}
			}
		}
		return list;
	}

	@SuppressWarnings("unused")
	public static void replaceTxtByStr(String path, Map<String, String> map) throws Exception {
		if (map.isEmpty()) {
			return;
		}
		String temp = null;
		File file = new File(path);
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		Writer pw = null;
		try {
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, "UTF-8");
			br = new BufferedReader(isr);
			StringBuffer buf = new StringBuffer();
			try {
				for (int j = 1; (temp = br.readLine()) != null; j++) {
					if (!"".equals(temp.trim())) {
						temp = replaceByMap(temp, map);
					}
					buf = buf.append(temp);
					buf = buf.append(System.getProperty("line.separator"));
				}
				pw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
				pw.write(buf.toString().toCharArray());
				pw.flush();
			} catch (IOException e) {
				e.printStackTrace();
				throw e;
			} finally {
				try {
					if (br != null)
						br.close();
					if (pw != null)
						pw.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw e;
				} finally {

				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw e;
		} finally {

		}
	}

	/**
	 * 静态化
	 * 
	 * @param templatePath
	 * @param homePagePath
	 * @param map
	 * @throws IOException
	 */
	public static void toStaticFile(String templatePath, String homePagePath, Map<String, String> map) {
		if (map.isEmpty()) {
			return;
		}
		String temp = null;
		File file = new File(templatePath);
		try {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			StringBuffer buf = new StringBuffer();
			for (int j = 1; (temp = br.readLine()) != null; j++) {
				if (!"".equals(temp.trim())) {
					temp = replaceByMap(temp, map);
				}
				buf = buf.append(temp);
				buf = buf.append(System.getProperty("line.separator"));
			}
			while ((temp = br.readLine()) != null) {
				buf = buf.append(System.getProperty("line.separator"));
				buf = buf.append(temp);
			}
			isr.close();
			fis.close();
			br.close();
			File outFile = new File(homePagePath);
			FileUtil.writeTextWithEncoding(outFile, buf.toString().getBytes(), "UTF-8");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * @param str
	 * @param map
	 * @return
	 */
	public static String replaceByMap(String str, Map<String, String> map) {
		Set<String> set = map.keySet();
		for (Iterator<String> it = set.iterator(); it.hasNext();) {
			String s = (String) it.next();
			String v = map.get(s);
			if (v != null)
				str = str.replaceAll(s, v);
		}
		return str;
	}

	/**
	 * 压缩图片 src输入图片路径 dest输出图片路径 压缩宽度 压缩高度
	 * 
	 * @param src
	 * @param dest
	 * @param w
	 * @param h
	 * @throws Exception
	 */
	public static boolean zoomImage(String src, String dest, String newName, int w, int h) throws Exception {
		double wr = 0, hr = 0;
		File srcFile = new File(src);
		String newDest = (dest + File.separator + newName);
		if (srcFile.exists()) {
			File destFile = new File(dest);
			if (!destFile.exists()) {
				destFile.mkdirs();
			}
			BufferedImage bufImg = ImageIO.read(srcFile);
			Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);
			wr = w * 1.0 / bufImg.getWidth();
			hr = h * 1.0 / bufImg.getHeight();
			AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
			Itemp = ato.filter(bufImg, null);
			try {
				ImageIO.write((BufferedImage) Itemp, newDest.substring(newDest.lastIndexOf(".") + 1), new File(newDest));
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
			}
		} else {
			return false;
		}
		return true;
	}

	/**
	 * 追加文件内容
	 * 
	 * @param filePath
	 * @param FileName
	 * @param content
	 */
	public static void appendFileContent(String filePath, String fileName, String content) {
		BufferedWriter out = null;
		try {
			mkDir(filePath);
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(Defines.getPath(filePath, fileName), true)));
			out.write(content);
			out.write("\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String readFileByLines(String filePath) {
		File file = new File(filePath);
		BufferedReader reader = null;
		StringBuffer sbf = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String str = null;
			// 一次读入一行,直到读入null为文件结束
			while ((str = reader.readLine()) != null) {
				sbf.append(str);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return sbf.toString();
	}

	public static void write(String path, String content) {
		BufferedWriter output = null;
		try {
			output = new BufferedWriter(new FileWriter(path));
			File f = new File(path);
			if (!f.exists()) {
				f.createNewFile();
			}
			output.write(content);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public final static void scale(String srcImageFile, String result, int maxWidth, int maxHeight) {
		try {
			createFileBaseDir(result);
			Thumbnails.of(srcImageFile).height(maxHeight).width(maxWidth).outputQuality(1f).toFile(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		BufferedReader bre = null;
		try {
//			String path = "f://aa/aa.txt";
//			Map<String, String> map = new HashMap<String, String>();
//			map.put("\\$\\{Content." + "test" + "\\}", "结果");
//			FileUtil.replaceTxtByStr(path, map);
			String str = "f://aa/hotel_content/";
			File file = new File(str);
			String[] strs = file.list();
			for (String s : strs) {
				File _file = new File(str + s);
				if (_file.isFile()&&_file.getName().toUpperCase().endsWith(".JPG")) {
					scale(str + s, str + "small/" + s, 764, 430);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	//读文本
	public static String readNumber(String prePath) throws IOException{
		File file = new File(prePath);
		if(!file.exists()){
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		FileInputStream in = null;
		byte[] fileContent = new byte[((Long)file.length()).intValue()];
		in = new FileInputStream(prePath);
		in.read(fileContent);
		in.close();	
		return new String(fileContent,"utf-8");
	}
	//写文本
	public static void writeNumber (String number,String prePath) throws IOException {
		File file = new File(prePath);
		FileOutputStream out = null;
		if(!file.exists()){
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		out = new FileOutputStream(prePath);
			out.write(number.getBytes());
			out.close();
	}
	

}
public interface Globals {
public static String VOD_POSTFIX = ".mp4|.mkv|.flv|.mov|.ts|.m2ts|.mpg|.m4v|.f4v";
	public static String MP3_POSTFIX = ".mp3";
	public static String PIC_POSTFIX = ".jpg|.gif|.png";
	}
相关标签: File