Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中如何用正则表达式替换txt文件中的单词_Java_Regex - Fatal编程技术网

java中如何用正则表达式替换txt文件中的单词

java中如何用正则表达式替换txt文件中的单词,java,regex,Java,Regex,我想用java替换txt文件中的一个单词。我已经有了正则表达式和从java读取txt文件的方法。但我不知道如何用mu正则表达式替换其中的一个单词 有什么建议或示例吗?将文件解析为一个字符串。然后用新单词替换word的所有实例 String response = "test string".replaceAll("regex here", "new text"); 然后将新文本写入文件 FileWriter writer = new FileWriter("out.txt"); write

我想用java替换txt文件中的一个单词。我已经有了正则表达式和从java读取txt文件的方法。但我不知道如何用mu正则表达式替换其中的一个单词


有什么建议或示例吗?

将文件解析为一个字符串。然后用新单词替换word的所有实例

 String response = "test string".replaceAll("regex here", "new text");
然后将新文本写入文件

 FileWriter writer = new FileWriter("out.txt");
 writer.write(response);

}

也许这个线程会对您有所帮助?您可以使用正则表达式来修改字符串,而不是文件。您需要其他工具从文件中读取文本并将其转换为字符串,然后应用正则表达式,然后将字符串存储到文件中。因此,您需要合适的读取器来读取文件中的文本,需要合适的写入器将文本写入文件。可能的重复请不要为此使用
字符串。它的性能非常糟糕,尤其是对于大文件。至少使用StringBuilder。是的,如果文件大小超过,则可以使用StringBuilder而不是字符串。
public class BTest
{
 public static void main(String args[])
     {
     try
         {
         File file = new File("file.txt");
         BufferedReader reader = new BufferedReader(new FileReader(file));
         String line = "", oldtext = "";
         while((line = reader.readLine()) != null)
             {
             oldtext += line + "\r\n";
         }
         reader.close();
         // replace a word in a file
         String newtext = oldtext.replaceAll("drink", "Love");

         //To replace a line in a file
         //String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");

         FileWriter writer = new FileWriter("file.txt");
         writer.write(newtext);writer.close();
     }
     catch (IOException ioe)
         {
         ioe.printStackTrace();
     }
 }