Java Iterate directory to find files and edit

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!");
}



發佈了107 篇原創文章 · 獲贊 11 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章