有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在文本文件中查找并替换单词(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) 个答案

  1. # 1 楼答案

    要将内容写入文件,需要使用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中的replace函数

    String str = someString.replace("OldText", "NewText");