使用 Java 在多个文本文件中查找和替换单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7779265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:25:25  来源:igfitidea点击:

Find and replace a word in several text files with Java?

java

提问by Pacific

How can I find and replace a word in several text files, using Java?

如何使用 Java 在多个文本文件中查找和替换单词?

Here's how I do it for a single String...

这是我如何为单个String...

public class ReplaceAll {

    public static void main(String[] args) {
        String str = "We want replace replace word from this string";  
        str = str.replaceAll("replace", "Done");
        System.out.println(str);
    }
}

回答by aioobe

Using FileUtilsfrom Commons IO:

FileUtilsCommons IO使用:

String[] files = { "file1.txt", "file2.txt", "file3.txt" };
for (String file : files) {
    File f = new File(file);
    String content = FileUtils.readFileToString(new File("filename.txt"));
    FileUtils.writeStringToFile(f, content.replaceAll("hello", "world"));
}

回答by RichW

You can read in the file using a FileReader wrapped by a BufferedReader, pulling it in line by line, perform the same replace on the string that you show in your question, and write it back out to a new file.

您可以使用由 BufferedReader 包装的 FileReader 读取文件,将其逐行拉入,对您在问题中显示的字符串执行相同的替换,然后将其写回新文件。

回答by Nikhil

This is the working code: Hope it helps!

这是工作代码:希望它有帮助!

import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;


public class TestIO {

 static StringBuilder sbword = new StringBuilder();
 static String dirname = null;
 static File[] filenames = null;
 static Scanner sc = new Scanner(System.in);

public static void main(String args[]) throws FileNotFoundException, IOException{
    boolean fileread = ReadFiles();

    sbword = null;
    System.exit(0);



}
private static boolean ReadFiles() throws FileNotFoundException, IOException{

    System.out.println("Enter the location of folder:");


    File file = new File(sc.nextLine());
    filenames = file.listFiles();
    String line = null;

    for(File file1 : filenames ){
    System.out.println("File name" + file1.toString());
    sbword.setLength(0); 
    BufferedReader br = new BufferedReader(new FileReader(file1));

    line = br.readLine();

    while(line != null){
        System.out.println(line);
        sbword.append(line).append("\r\n");
        line = br.readLine();
        }

    ReplaceLines();
    WriteToFile(file1.toString());

    }

    return true;    
}

private static void ReplaceLines(){
    System.out.println("sbword contains :" + sbword.toString());
    System.out.println("Enter the word to replace from each of the files:");
    String from = sc.nextLine();
    System.out.println("Enter the new word");
    String To = sc.nextLine();

    //StringBuilder sbword = new StringBuilder(stbuff);
    ReplaceAll(sbword,from,To);



}
private static void ReplaceAll(StringBuilder builder, String from, String to){
    int index = builder.indexOf(from);
    while(index != -1){
        builder.replace(index, index + from.length(), to);
        index += to.length();
        index = builder.indexOf(from,index);
    }
}
private static void WriteToFile(String filename) throws IOException{
   try{
    File file1 = new File(filename);
    BufferedWriter bufwriter = new BufferedWriter(new FileWriter(file1));
    bufwriter.write(sbword.toString());
    bufwriter.close();

    }catch(Exception e){
         System.out.println("Error occured while attempting to write to file: " +     e.getMessage());
    }

}

}

import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;


public class TestIO {

 static StringBuilder sbword = new StringBuilder();
 static String dirname = null;
 static File[] filenames = null;
 static Scanner sc = new Scanner(System.in);

public static void main(String args[]) throws FileNotFoundException, IOException{
    boolean fileread = ReadFiles();

    sbword = null;
    System.exit(0);



}
private static boolean ReadFiles() throws FileNotFoundException, IOException{

    System.out.println("Enter the location of folder:");


    File file = new File(sc.nextLine());
    filenames = file.listFiles();
    String line = null;

    for(File file1 : filenames ){
    System.out.println("File name" + file1.toString());
    sbword.setLength(0); 
    BufferedReader br = new BufferedReader(new FileReader(file1));

    line = br.readLine();

    while(line != null){
        System.out.println(line);
        sbword.append(line).append("\r\n");
        line = br.readLine();
        }

    ReplaceLines();
    WriteToFile(file1.toString());

    }

    return true;    
}

private static void ReplaceLines(){
    System.out.println("sbword contains :" + sbword.toString());
    System.out.println("Enter the word to replace from each of the files:");
    String from = sc.nextLine();
    System.out.println("Enter the new word");
    String To = sc.nextLine();

    //StringBuilder sbword = new StringBuilder(stbuff);
    ReplaceAll(sbword,from,To);



}
private static void ReplaceAll(StringBuilder builder, String from, String to){
    int index = builder.indexOf(from);
    while(index != -1){
        builder.replace(index, index + from.length(), to);
        index += to.length();
        index = builder.indexOf(from,index);
    }
}
private static void WriteToFile(String filename) throws IOException{
   try{
    File file1 = new File(filename);
    BufferedWriter bufwriter = new BufferedWriter(new FileWriter(file1));
    bufwriter.write(sbword.toString());
    bufwriter.close();

    }catch(Exception e){
         System.out.println("Error occured while attempting to write to file: " +     e.getMessage());
    }

}

}