在文本文件中查找并替换单词(Java GUI)
我希望创建一个“查找并替换”java应用程序,它会提示用户调用文本文件,将其打印到新文件中,要求用户输入搜索词或短语,并用一个词替换该搜索词。这是我目前掌握的代码。我可以很好地读取第一个文件中的内容,但无法将第一个文件中的内容写入另一个文件。这一切都是在下面的GUI代码中完成的
String loc = jTextField1.getText(); //gets location of initial file or "source"
String file = jTextField4.getText(); //new file path
String find = jTextField2.getText(); //find word inputted by user
String word = jTextField3.getText(); //replace "find" with word inputted by user
String line = null;
try {
BufferedReader br = new BufferedReader(new FileReader(loc));
while ((line = br.readLine()) !=null)
} catch (FileNotFoundException ex) {
Logger.getLogger(Assign6GUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Assign6GUI.class.getName()).log(Level.SEVERE, null, ex);
}
# 1 楼答案
要将内容写入文件,需要使用BufferedWriter
要替换字符串中的单词,应该使用java中的replace函数