目录
题目:**18.31 (替换单词)
习题思路
代码示例
运行结果
替换前
替换后
题目:**18.31 (替换单词)
编写一个程序,递归地用一个新单词替换某个目录下的所有文件中出现的某个单词。从命令行如下传递参数:
java Exercise18_31 dirName oldWord newWord
-
习题思路
- (读取路径方法)和18.28题差不多,把调用读取文件单词在文件内出现的次数改成调用读取并修改文件方法。Java语言程序设计基础篇_编程练习题*18.28 (非递归目录大小)-CSDN博客
- (读取并修改文件方法)传入文件和单词,逐行读取文件,将找到的单词替换为新的字符串,并将每一行(不管是否修改)添加到一个字符串中,在读取结束后向文件内写入字符串。.
- (main方法)读取传入的路径和单词,调用读取路径方法。
-
代码示例
编程练习题18_31ReplaceWords.java
package chapter_18;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class 编程练习题18_31ReplaceWords {public static void main(String[] args) throws FileNotFoundException,IOException{if(args.length != 3) {System.out.println("Usage: java 编程练习题18_30WordCount dirName oldWord newWord");System.exit(0);}String path = args[0];String oldWord = args[1];String newWord = args[2];File file = new File(path);readPath(file, oldWord,newWord);System.out.println("Successfully replaced word.");}public static void readPath(File file,String oldWord,String newWord) throws FileNotFoundException,IOException{ArrayList<File> files = new ArrayList<File>();files.add(file);while(!files.isEmpty()) {ArrayList<File> newList = new ArrayList<File>();for(File f : files) {if(f.isFile()) readFile(f, oldWord,newWord);else {File[] fileList = f.listFiles();if(fileList != null) {for(File f2:fileList){if(f2.isDirectory())newList.add(f2);else readFile(f2, oldWord,newWord);}}}}files = newList;}}public static void readFile(File file, String oldWord,String newWord) throws FileNotFoundException,IOException {StringBuilder str = new StringBuilder();try(Scanner input = new Scanner(file)){while(input.hasNextLine()) {String line = input.nextLine();Pattern pattern = Pattern.compile("\\b" + Pattern.quote(oldWord) + "\\b");Matcher matcher = pattern.matcher(line); if(matcher.find()) {line = matcher.replaceAll(newWord);}str.append(line+"\n");}}try(FileWriter output = new FileWriter(file)){output.write(str.toString());}}
}
-
运行结果
-
替换前
-
替换后