簡體   English   中英

如何從Java中的文本文件中刪除整數記錄?

[英]How to delete integer record from text file in java?

我有一個簡單的問題...我編寫此代碼來刪除以字符串開頭的記錄,但是當嘗試應用此代碼來刪除另一個以整數開頭的記錄時,這給了我一個錯誤

這是我的代碼:

public void deleteSupplier(String company) throws FileNotFoundException, IOException
{
    File inputFile = new File("C:\\Users\\فاطمة\\Downloads\\suppliers.txt"); // Your file  
    File tempFile = new File("C:\\Users\\فاطمة\\Downloads\\suppliers2.txt"); // temp file

    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

    String currentLine;

    while((currentLine = reader.readLine()) != null) 
    {
        if(currentLine.contains(company))
            continue;

        writer.write(currentLine);
        writer.newLine();
    }

    writer.close();
    reader.close();

    File inputFile1 = new File("C:\\Users\\فاطمة\\Downloads\\suppliers.txt"); // Your file  

    File tempFile1 = new File("C:\\Users\\فاطمة\\Downloads\\suppliers2.txt"); // temp file

    inputFile1.delete();
    boolean successful = tempFile1.renameTo(inputFile1);

    if(successful == true)
        System.out.println("Supplier deleted successfully");

    else if(successful == false)
        System.out.println("Error: deleting failed, supplier might not be found.");
}

例如我有這樣的記錄:

   Hamada Port 111
   Hobeee Jack 447

該代碼對此很好用,但是當嘗試將代碼用於這樣的記錄時

   1 Hamada 147
   7 Hobeee 444

它給我錯誤。

注意:我用過:

   int id

代替

   String company

並在函數中使用id代替company:

        currentLine.contains(id);

但它給出了錯誤。

請幫忙嗎?

由於您正在調用String類的“包含”方法,因此您只能給CharSequence子類的實例作為像String這樣的參數(例如,對於字符串的情況)。 由於Integer不是CharSequence接口的子類,因此必須先將其轉換后才能應用到“包含”方法。 將int值轉換為String將是方法。

currentLine.contains(company)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM