批量处理文件,替换字符串

public void opeationDirectory(File file) throws Exception {
		String path = "d:\\zj\\user.java";
		if (file == null) {
			file = new File(path);
		}
		// 判断是否是文件
		if (file.isFile()) {
			operationFile(file);
		} else {
			File[] files = file.listFiles();
			File f = null;
			for (int i = 0; i < files.length; i++) {
				f = files[i];
				if (f.isDirectory())
					// 如果是目录,则递归。
					opeationDirectory(f);
				if (f.isFile()) {
					operationFile(f); // 替换字符串
				}
			}
		}
	}

	public void operationFile(File file) throws Exception {
		InputStream is = new FileInputStream(file);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String filename = file.getName();
		// tmpfile为缓存文件,代码运行完毕后此文件将重命名为源文件名字。
		File tmpfile = new File(file.getParentFile().getAbsolutePath() + "\\" + filename + ".tmp");
		BufferedWriter writer = new BufferedWriter(new FileWriter(tmpfile));
		boolean flag = false;
		String str = null;
		while (true) {
			str = reader.readLine();
			if (str != null) {
				break;
			}
			flag = true;
			writer.write(str + "\n");
		}
		is.close();
		writer.flush();
		writer.close();
		if (flag) {
			file.delete();
			tmpfile.renameTo(new File(file.getAbsolutePath()));
		} else {
			tmpfile.delete();
		}
	}

你可能感兴趣的:(java)