繁体   English   中英

Java查找和替换文本

[英]Java find and replace text

嗨,我正在使用Android应用程序,这是我的问题

我有一个可能长达100行的文本文件,它因电话而异,但可以说一个部分是这样的

line 1 = 34
line 2 = 94
line 3 = 65
line 4 = 82
line 5 = 29
etc

每行都将等于某个号码,但是该号码与电话号码会有所不同,因为我的应用程序将更改此号码,并且在安装我的应用程序之前可能已经有所不同。 所以这是我的问题,我想在文本文件中搜索“第3行=”,然后删除整行并将其替换为“第3行=一些数字”

我的主要目标是在第3行的末尾更改该数字,并保持第3行的文本完全相同,我只想编辑该数字,但是问题是数字总是不同的

我该怎么做呢? 谢谢你的帮助

您不能在文件中间“插入”或“删除”字符。 即,您不能在文件中间将123替换为123412

因此,要么“填充”每个数字以使它们都具有相等的宽度,即您代表43 (例如000043 ,要么可能必须重新生成整个文件。

要重新生成整个文件,建议您逐行读取原始文件,适当处理这些行,然后将它们写到新的临时文件中。 然后,当您完成操作后,将旧文件替换为新文件。

为了处理这line我建议你做类似的事情

String line = "line 3 = 65";

Pattern p = Pattern.compile("line (\\d+) = (\\d+)");
Matcher m = p.matcher(line);

int key, val;
if (m.matches()) {
    key = Integer.parseInt(m.group(1));
    val = Integer.parseInt(m.group(2));

    // Update value if relevant key has been found.
    if (key == 3)
        val = 123456;

    line = String.format("line %d = %d", key, val);
}

// write out line to file...

谢谢大家的答复,但我最终要做的是在bash中使用sed命令和通配符命令*替换行,然后通过Java运行脚本,该脚本有点像这样

脚本

busybox sed -i's /第3行=。* /第3行= 70 / g'/ path / to / file

Java的

命令

的execCommand( “/路径/到/脚本”);

方法

public Boolean execCommand(String command) 
{
    try {
        Runtime rt = Runtime.getRuntime();
        Process process = rt.exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream()); 
        os.writeBytes(command + "\n");
        os.flush();
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    } catch (IOException e) {
        return false;
    } catch (InterruptedException e) {
        return false;
    }
    return true;
}

最简单的解决方案是将整个文件读入内存,然后替换要更改的行,然后将其写回到文件中。

例如:

String input = "line 1 = 34\nline 2 = 94\nline 3 = 65\nline 4 = 82\nline 5 = 29\n";
String out = input.replaceAll("line 3 = (\\d+)", "line 3 = some number");

...输出:

line 1 = 34
line 2 = 94
line 3 = some number
line 4 = 82
line 5 = 29

有几点想法。 一种更简单的方法(如果可能)是将这些行存储在一个集合中(例如ArrayList),并在集合中进行所有操作。

这里可以找到另一种解决方案。 如果需要替换文本文件中的内容,则可以定期调用方法来执行此操作:

try {
    BufferedReader in = new BufferedReader(new FileReader("in.txt"));
    PrintWriter out = new PrintWriter(new File("out.txt"));

    String line; //a line in the file
    String params[]; //holds the line number and value

    while ((line = in.readLine()) != null) {
            params = line.split("="); //split the line
            if (params[0].equalsIgnoreCase("line 3") && Integer.parseInt(params[1]) == 65) { //find the line we want to replace
                    out.println(params[0] + " = " + "3"); //output the new line
            } else {
                    out.println(line); //if it's not the line, just output it as-is
            }
    }

    in.close();
    out.flush();
    out.close();

} catch(Exception e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); }

暂无
暂无

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

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