繁体   English   中英

使用 Java 在文本文件中查找和替换单词

[英]Find and replace words in a text file using Java

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

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

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

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

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
    }
}

如果我了解情况,也许问题在于您正在替换相同的字符串,并存储在不同的变量中,

试试看:

  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();
         }
     }

现有答案的更好版本:

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 唯一的区别是后者将第一个参数解释为正则表达式而不是文字字符串。 两者都替换所有出现的,在这种情况下不需要正则表达式,并且可能只会由于特殊字符而导致不需要的行为。

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

     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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM