【问题标题】:Find and replace words in a text file using Java使用 Java 查找和替换文本文件中的单词
【发布时间】:2015-03-15 01:08:07
【问题描述】:

我正在尝试使用 Java 查找和替换文本文件中的某些单词。我的代码在一定程度上有效,但是我得到的输出是错误的。 我需要用用户输入替换文本文件中一行中的多个单词。但是,当我运行我的代码时,该行会为我尝试替换的每个单词复制一次。

例如,如果我想替换以下 3 个单词:

python ycsb phase db -s -P /home/james/YCSB/workloads/workloada -p 
db.url=db://IP:port -p db.database=name

我最终得到了 3 个副本,每个副本都替换了一个不同的单词。而不是替换所有 3 个必需单词的 1 行。 下面提供了代码,在此先感谢。

public static void main(String[] args) {

    System.out.print("Phase: ");
    Scanner sp = new Scanner(System.in);
    String p = sp.nextLine();
    
    System.out.print("Database: ");
    Scanner sd = new Scanner(System.in);
    String d = sd.nextLine();
    
    System.out.print("IP address: ");
    Scanner sip = new Scanner(System.in);
    int ip = sip.nextInt();
     
    try {
        File file = new File("C://users//James//Desktop//newcommand.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = "", oldtext = "";
        while((line = reader.readLine()) != null) {
            oldtext += line + "\r\n";
        }
        reader.close();
       
        String phase  = oldtext.replaceAll("phase", "" + p);
        String database = oldtext.replaceAll("db", "" + d);
        String ips = oldtext.replaceAll("IP", "" + ip);
        
        FileWriter writer = new FileWriter("C://users//James//Desktop//newcommand.txt");
        writer.write(phase + ips + database);
        writer.close();
    } catch (IOException e) {
        // handle e
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    如果我对这种情况理解得很好,也许问题是你正在替换相同的字符串,并存储在不同的 var 中,

    试试看:

      public static void main(String[] args) {
            System.out.print("Phase: ");
            Scanner sp = new Scanner(System.in);
            String p;
            p = sp.nextLine();
    
            System.out.print("Database: ");
            Scanner sd = new Scanner(System.in);
            String d;
            d = sd.nextLine();
    
            System.out.print("IP address: ");
            Scanner sip = new Scanner(System.in);
            int ip = sip.nextInt();
    
            {
             try
                 {
                 File file = new File("C://users//James//Desktop//newcommand.txt");
                 BufferedReader reader = new BufferedReader(new FileReader(file));
                 String line = "", oldtext = "";
                 while((line = reader.readLine()) != null)
                     {
                     oldtext += line + "\r\n";
                 }
                 reader.close();
    
                 String replacedtext  = oldtext.replaceAll("phase", "" + p);
                 replacedtext = replacedtext.replaceAll("db", "" + d);
                 replacedtext = replacedtext.replaceAll("IP", "" + ip);
    
                 FileWriter writer = new FileWriter("C://users//James//Desktop//newcommand.txt");
                 writer.write(replacedtext);
    
    
                 writer.close();
    
             }
             catch (IOException ioe)
                 {
                 ioe.printStackTrace();
             }
         }
    

    【讨论】:

    • @user3504042:只是一个评论:你可以使用 String.replace() 来完成这个任务。 String.replaceAll() 将令牌视为正则表达式,可能会也可能不会产生所需的结果
    【解决方案2】:

    现有答案的更好版本:

    public static void main(String[] args)
    {
        Scanner sp = new Scanner(System.in);
        System.out.print("Phase: ");
        String pstr = s.nextLine();
        System.out.print("Database: ");
        String dstr = s.nextLine();
        System.out.print("IP address: ");
        String ipstr = String.valueOf(s.nextInt());
    

    读取输入后,我们可以使用两种有效的方法从文件中读取,然后写回。首先我建议写入一个临时文件(这也是sed 替换文件中文本的方式)。这种方法的一个优点是最后一步可能是原子操作。

        File f = new File("C://users//James//Desktop//newcommand.txt");
        File ftmp = new File("C://users//James//Desktop//~tmp.newcommand.txt", ".txt");
        try
        {
            BufferedReader br = new BufferedReader(new FileReader(f));
            BufferedWriter bw = new BufferedWriter(new FileWriter(ftmp));
            String ln;
            while((ln = br.readLine()) != null)
            {
                bw.write(ln
                    .replace("phase", pstr)
                    .replace("db", dstr)
                    .replace("IP", ipstr)
                );
                bw.newLine();
            }
            br.close();
            bw.close();
            Files.move(ftmp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    

    或者,如果您真的不想拥有一个临时文件,从而将所有内容都保存在 RAM 中,请使用以下代码:

        File f = new File("C://users//James//Desktop//newcommand.txt");
        try
        {
            String ENDL = System.getProperty("line.separator");
    
            StringBuilder sb = new StringBuilder();
    
            BufferedReader br = new BufferedReader(new FileReader(f));
            String ln;
            while((ln = br.readLine()) != null)
            {
                sb.append(ln
                    .replace("phase", pstr)
                    .replace("db", dstr)
                    .replace("IP", ipstr)
                ).append(ENDL);
            }
            br.close();
    
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            bw.write(sb.toString());
            bw.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    

    不要忘记右括号;)

    }
    

    请注意 - 与其他答案相反 - 我使用的是 .replace 而不是 .replaceAll。唯一的区别是后者将第一个参数解释为正则表达式而不是文字字符串。两者都替换所有出现,在这种情况下不需要正则表达式,并且可能只会由于特殊字符而导致不需要的行为。

    【讨论】:

      【解决方案3】:

      尽管我没有写任何东西所以我没有测试它,我认为问题在这部分代码中很明显:

           String phase  = oldtext.replaceAll("phase", "" + p);
           String database = oldtext.replaceAll("db", "" + d);
           String ips = oldtext.replaceAll("IP", "" + ip);
      
           FileWriter writer = new FileWriter("C://users//James//Desktop//newcommand.txt");
           writer.write(phase + ips + database);
      

      您正在创建 3 个新字符串。第一个字符串替换了phase,第二个替换了db,第三个替换了IP。这显然不是你想要的。你应该这样做:

           String phase  = oldtext.replaceAll("phase", "" + p);
           String database = phase.replaceAll("db", "" + d);
           String ips = database.replaceAll("IP", "" + ip);
      
           FileWriter writer = new FileWriter("C://users//James//Desktop//newcommand.txt");
           writer.write(ips);
      

      编辑:哎呀,太晚了^_^

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-04
        • 2011-04-25
        • 1970-01-01
        • 1970-01-01
        • 2017-11-18
        • 2021-01-12
        • 2020-12-20
        • 2011-08-20
        相关资源
        最近更新 更多