2011-05-06 72 views
0

嗨,我工作的一个Android应用程序,这是我的问题Java的查找和替换文本

我有一个文本文件,它也许是100行从手机到不同的手机,但让说,一节是像这

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

每条线路将等于一定数量然而,这个数字将是手机不同的,因为我的应用程序将改变这个数字并安装我的应用程序之前,它可能已经是不同的。所以这里是我的问题,我想搜索文本文件的说“行3 =”,然后删除整行,并将其替换为“行3 =某些数字”

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

我该如何去做这件事?感谢您的任何帮助

回答

2

的答复谢谢你们,但我最终使用了sed的做在bash和通配符命令*命令替换行,然后刚跑出通过Java哪去有点像这样

脚本

busybox的sed的-i“S/L脚本3 =。* /线3 = 70/G” /路径/到/文件

爪哇

命令

的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; 
} 
+1

我认为这是一个黑客。改为正确使用,并使用先前接受的答案。 – dacwe 2011-05-12 11:05:33

2

您不能在文件的中间“插入”或“删除”字符。也就是说,你不能用文件中间的123412代替123。因此,要么你“填充”每个数字,因此它们都具有相等的宽度,即,例如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... 
0

最简单的办法是阅读整个文件到内存中,然后替换线要更改,然后将它写回文件。

对于exmple:

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 
0

一对夫妇的想法。一个更简单的方法来做到这一点(如果可能的话)将是将这些行存储在集合中(如ArrayList),并在集合中进行所有操作。

另一种解决方案可以找到here。如果你需要一个文本文件中的内容替换,你可以定期调用一个方法来做到这一点:

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

+2

''==不处理字符串 – dacwe 2011-05-06 14:52:46

+0

好对象,我会作出修改。 – Kyle 2011-05-06 16:39:02