2013-10-31 23 views
0

我有一個數組列表,其中包含來自文本文件的數據。從數組列表中刪除字符串Java

文本文件的結構是這樣

1,2,Name,2,itemName 

我的代碼:

String Cid = "1"; 
String Tid = "1"; 
//Help 

File iFile = new File("Records"); 
BufferedReader yourfile = new BufferedReader(new FileReader(iFile)); 
FileWriter writer = new FileWriter(iFile);  
String dataRow = yourfile.readLine(); 

    while (dataRow != null){ 

     String[] dataArray = dataRow.split(","); 

     if(Cid.equals(dataArray[1]) && Tid.equals(dataArray[3])) 

      dataRow = yourfile.readLine(); 


     else{ 
      System.out.print(dataRow); 
      writer.append(dataArray[0]+", "); 
      writer.append(dataArray[1]+", "); 
      writer.append(dataArray[2]+", "); 
      writer.append(dataArray[3]+", "); 
      writer.append(dataArray[4]); 
      writer.append(System.getProperty("line.separator")); 
      dataRow = yourfile.readLine(); 
     } 
    } 
    writer.flush(); 
    writer.close(); 

} 我希望能夠刪除的記錄,其中名稱編號和項目ID匹配。

我已閱讀的有關從數組列表中刪除項目的所有內容只會根據項目位置進行討論。任何幫助將非常感激。

+0

你已經嘗試過什麼?你的代碼在哪裏? –

+3

用迭代器遍歷它並將其刪除。儘管你的文本文件結構對我來說毫無意義。 –

+0

現在有意義嗎? – user2924202

回答

0
String Cid = "1"; 
String Tid = "1"; 

File iFile = new File("Records"); 
BufferedReader yourfile = new BufferedReader(new FileReader(iFile)); 
BufferedReader yourfile2 = new BufferedReader(new FileReader(iFile)); 

int total=0; 
String rec=yourfile2.readLine(); 
while (rec != null){ // count total records (rows) 
    total++; 
    rec=yourfile2.readLine(); 
} 

String dataRow = yourfile.readLine(); 
String[] allTemp[]=new String[total][]; //create array of an array with size of the total record/row 
int counter=0; 

while (dataRow != null){ 

    String[] dataArray = dataRow.split(","); 

    if(Cid.equals(dataArray[1]) && Tid.equals(dataArray[3])) 
     dataRow = yourfile.readLine(); // skip current row if match found 
    else{ 
     allTemp[counter]=dataArray; //if match not found, store the array into another array 
     dataRow = yourfile.readLine(); 
     counter++; //index for allTemp array. note that counter start from zero and no increment if the current row is skipped 
     }  
} 
FileWriter writer = new FileWriter(iFile); //create new file which will replace the records file. here, all desired records from file already stored in allTemp array 
for (String[] arr : allTemp){ 
    //check nullity of array inside the array(record). 
    if(arr!=null){ 
     for(int i=0;i<arr.length;i++){ 
      writer.append(arr[i]); 
       if(i<arr.length-1) //add "," in every column except in the last column 
        writer.append(","); 
     } 
     writer.append(System.getProperty("line.separator")); 
    } 
} 
writer.flush(); 
writer.close(); 

更新:您可以刪除String[] temp;temp = new String[dataArray.length];,因爲它從來沒有實際使用

+0

非常好的例子感謝您花時間寫下它。我將if語句更改爲(Cid.equals(dataArray [1])&& Tid.equals(dataArray [3])),因爲兩者不匹配。對不起,如果我不清楚 – user2924202

+0

沒問題。希望能幫助到你。是的,你應該改變if語句,因爲我不太瞭解你的txt文件結構。 – Baby

+0

我改變了它,但現在它只是刪除文本文件中的所有內容。爲了清楚,用戶將在一行中輸入2個數字Cid和Tid,我想刪除該行。抱歉,我剛剛接觸編程只是爲了讓我的頭腦圍繞代碼所做的一切。 – user2924202

0

我想你需要遍歷數組列表中的每個元素,併爲每個String創建一個java.util.StringTokenizer作爲分隔符(我假設Name或itemName中沒有逗號)。

然後獲得第二個和第四個標記並比較它們。如果匹配,然後刪除該項目。

這可能是最有效的,如果你使用一個for循環,從ArrayList的末尾開始,並移動到第0個元素,按索引刪除項目,當你找到它們。

+1

StringTokenizer是一個遺留類。應該使用'String.split()' –

+0

謝謝,我將盡快發佈並回復 – user2924202

+0

我建議StringTokenizer,因爲雖然它是「遺留」,但它不被棄用。這裏的分割是一個簡單的字符,String.split()需要初始化/調出昂貴的正則表達式引擎。我認爲StringTokenizer可能更合適,但可以使用。 –

0
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.Scanner; 

public class Neat { 

    public static void main(String... string) throws FileNotFoundException { 

     File file = new File("c:/AnyFile.txt"); 
     Scanner fileScanner = new Scanner(file); 

     while (fileScanner.hasNextLine()) { 
      String text = fileScanner.nextLine(); 
      String[] data = text.split(","); 

      int recordId = Integer.parseInt(data[0]); 
      int nameId = Integer.parseInt(data[1]); 
      String name = data[2]; 
      int itemId = Integer.parseInt(data[3]); 
      String itemName = data[4]; 

      if (nameId == itemId) { 
       removeLineFromFile(file, text); 
      } 

     } 

    } 

    public static void removeLineFromFile(File file, String lineToRemove) { 

     try { 

      File inFile = file; 

      if (!inFile.isFile()) { 
       System.out.println("Parameter is not an existing file"); 
       return; 
      } 


      // Construct the new file that will later be renamed to the original 
      // filename. 
      File tempFile = new File(inFile.getAbsolutePath() + ".tmp"); 

      BufferedReader br = new BufferedReader(new FileReader(file)); 
      PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); 

      String line = null; 

      // Read from the original file and write to the new 
      // unless content matches data to be removed. 
      while ((line = br.readLine()) != null) { 

       if (!line.trim().equals(lineToRemove)) { 

        pw.println(line); 
        pw.flush(); 
       } 
      } 
      pw.close(); 
      br.close(); 

      // Delete the original file 
      if (!inFile.delete()) { 
       System.out.println("Could not delete file"); 
       return; 
      } 

      // Rename the new file to the filename the original file had. 
      if (!tempFile.renameTo(inFile)) 
       System.out.println("Could not rename file"); 

     } catch (FileNotFoundException ex) { 
      ex.printStackTrace(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 


} 

剛剛得到的東西,你想

+0

但是在代碼中,您必須給予您正在閱讀的文件的777權限以修改文件... –

相關問題