Java Iterate directory to find files and edit

本文介绍了一个简单的程序,用于递归搜索指定目录及其子目录下的所有XML文件,并对这些文件进行特定模式的批量修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

After mannually modified about 100 pages, I'm tired of doing that. So it's better to write a small program to deal with those thing.

1. We need to find those files which we need to modify in different directories. My example is to match all .xml file.

public static void searchFile(String sDir) {
		File[] faFiles = new File(sDir).listFiles();
		for (File file : faFiles) {
			if (file.getName().matches("^(.*xml)")) {
				System.out.println(file.getAbsolutePath());
				editFile(file.getAbsolutePath()); //Call another function
			}
			if (file.isDirectory()) {
				searchFile(file.getAbsolutePath());
			}
		}
}

2. Modify the file as we want.

public static void editFile(String fileName) {
		File f = new File(fileName);

		FileInputStream fs = null;
		InputStreamReader in = null;
		BufferedReader br = null;

		StringBuffer sb = new StringBuffer();

		String textinLine;

		try {
			fs = new FileInputStream(f);
			in = new InputStreamReader(fs);
			br = new BufferedReader(in);

			while (true) {
				textinLine = br.readLine();

				if (textinLine == null)
					break;

				if (textinLine.endsWith("</__uuid>")) { //Condition to modify file
					textinLine = "<__uuid></__uuid>";
				}

				System.out.println(textinLine);
				sb.append(textinLine + "\r\n");
			}

			fs.close();
			in.close();
			br.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
                /*Write the file back*/
		try {
			FileWriter fstream = new FileWriter(f);
			BufferedWriter outobj = new BufferedWriter(fstream);
			outobj.write(sb.toString());
			outobj.close();

		} catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
		}
	}
3. In your main method, call searchFile method.

public static void main(String[] args) {
		searchFile("your file directory!");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值