2011-05-06 162 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