2012-09-29 77 views
2

我的意思是,我想從我的android文本中刪除行。我如何刪除? 我不想讀取一個txt並使用刪除行創建另一個txt。我想從我現有的txt刪除行。 謝謝。如何從txt刪除行?

+0

第一行?最後一行?中線? – Simon

+0

例如21.line –

+0

給我樣本? –

回答

5

這是一個非常棘手的問題,儘管它看起來微不足道。在可變行長的情況下,可能您唯一的選擇是逐行讀取文件以識別目標行的offsetlength。然後複製文件的以下部分,從offset開始,最終將文件長度截斷爲其原始大小減去目標行的長度。我使用RandomAccessFile來訪問內部指針,並且還可以通過行讀取。

此程序需要兩個命令行參數:

  • args[0]是文件名
  • args[1]是目標線數(從1開始:第一行是#1)
public class RemoveLine { 
    public static void main(String[] args) throws IOException { 
     // Use a random access file 
     RandomAccessFile file = new RandomAccessFile(args[0], "rw"); 
     int counter = 0, target = Integer.parseInt(args[1]); 
     long offset = 0, length = 0; 

     while (file.readLine() != null) { 
      counter++; 
      if (counter == target) 
       break; // Found target line's offset 
      offset = file.getFilePointer(); 
     } 

     length = file.getFilePointer() - offset; 

     if (target > counter) { 
      file.close(); 
      throw new IOException("No such line!"); 
     } 

     byte[] buffer = new byte[4096]; 
     int read = -1; // will store byte reads from file.read() 
     while ((read = file.read(buffer)) > -1){ 
      file.seek(file.getFilePointer() - read - length); 
      file.write(buffer, 0, read); 
      file.seek(file.getFilePointer() + length); 
     } 
     file.setLength(file.length() - length); //truncate by length 
     file.close(); 
    } 
} 

Here is the full code,包括一個JUnit測試用例。使用這種解決方案的優勢在於它應該對內存完全可擴展,即由於它使用固定緩衝區,其內存需求是可預測的,並且不會根據輸入文件大小而改變。

3

嘗試將文件存儲到字符串緩衝區中替換您想要替換的文件,然後完全替換文件的內容。

+0

給樣品? –

+0

我嘗試感謝您的建議 –

0

您可以通過複製文件中的其餘數據,然後清空文件並最終寫入複製的數據來刪除一行.Thr下面的代碼搜索要刪除的字符串並跳過要複製到stringBuider中的代碼。 stringBuilder的內容在沖洗後被複制到同一文件

  try { 
       InputStream inputStream = openFileInput(FILENAME); 
       FileOutputStream fos = openFileOutput("temp", Context.MODE_APPEND); 

       if (inputStream != null) { 
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
        String receiveString = ""; 
        String deleteString = "<string you want to del>"; 
        StringBuilder stringBuilder = new StringBuilder(); 

        while ((receiveString = bufferedReader.readLine()) != null) { 
         if (!reciveString.equals(deleteline)) { 
          stringBuilder.append(receiveString); 
         } 
        } 
        fos.flush(); 

        fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
        fos.write(stringBuilder.toString().getBytes()); 
        fos.close(); 
        inputStream.close(); 
        }