我正在寻找创建一个查找并替换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);
}
答案 0 :(得分:0)
要将内容写入文件,您需要使用BufferedWriter
public static void writetoFile(String str, String FILE_PATH, String FILENAME ) {
BufferedWriter writer = null;
try {
File file = new File(FILE_PATH);
// if file doesnt exists, then create it
if (!file.exists()) {
file.mkdir();
}
file = new File(FILE_PATH + FILENAME);
file.createNewFile();
writer = new BufferedWriter(new FileWriter(file));
writer.write(str);
} catch (IOException e) {
LOGGER.debug(e);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (Exception e) {
LOGGER.debug(e);
}
}
}
要替换字符串中的单词,您应该使用java中的替换函数
String str = someString.replace("OldText", "NewText");