2017-02-04 6 views
1

ファイルから特定の行を削除しようとしています。しかし、私はテキストファイルから特定の行を削除する際に問題があります。さんが言ってみましょう、私は次のファイルにブルーベリーを削除する私のテキストファイル:特定の行をテキストファイルから削除する

旧リストのテキストファイル:

Chocolate 
Strawberry 
Blueberry 
Mango 

新規一覧をテキストファイル:

Chocolate 
Strawberry 
Mango 

私は私のJavaを実行しようとしました私は削除のために入力し、テキストファイルから行を削除しませんでした。

出力: 削除してください: D ブルーベリー 削除:私は私のテキストファイルを開くとブルーベリー

、それは単語「ブルーベリー」だけでループし続けます。

テキストファイル:

Blueberry 
Blueberry 
Blueberry 
Blueberry 
Blueberry 
Blueberry 
Blueberry 
Blueberry 

私の質問は、テキストファイルから特定の行を削除する方法ですか?ここで

は私のJavaコードです:

String input="Please delete: "; 
System.out.println(input); 

try 
     {   
      BufferedReader reader = new BufferedReader 
        (new InputStreamReader (System.in)); 
      line = reader.readLine(); 

      String inFile="list.txt"; 
      String line = ""; 


      while(!line.equals("x")) 
      { 
       switch(line) 
       {     

        case "d": 

        line = reader.readLine(); 
        System.out.println("Remove: " + line); 
        String lineToRemove=""; 

        FileWriter removeLine=new FileWriter(inFile); 
        BufferedWriter change=new BufferedWriter(removeLine); 
        PrintWriter replace=new PrintWriter(change); 

        while (line != null) { 
         if (!line.trim().equals(lineToRemove)) 
         { 
          replace.println(line); 
          replace.flush(); 
         } 
        } 
        replace.close(); 
        change.close(); 
        break; 

       } 
       System.out.println(input); 
       line = reader.readLine(); 


      } 

     } 
     catch(Exception e){ 
      System.out.println("Error!"); 
     } 
+0

あなたは初めての行を読んだだけです。ファイル内の他の行は決して読み取れません。 – MadProgrammer

+1

'lineToRemove'を空白以外の場所に設定する場所は表示されません。ユーザーが入力した行にlineToRemoveを設定する必要があります。 –

答えて

1

line = reader.readLine(); 
//... 
while (line != null) { 
    if (!line.trim().equals(lineToRemove)) 
    { 
     replace.println(line); 
     replace.flush(); 
    } 
} 

は基本的に、あなたはファイルの最初の行を読み、それを繰り返し比較する...のは、あなたのコードを簡単に見てみましょうlineToRemoveと、永遠に。このループは決して終了しません。

これは概念の証明であり、必要に応じて変更する必要があります。

基本的に、あなたがやっていることを確認するために必要なもの、あなたが入力ファイルの各行を読んでいるされて、それ以上のラインがなくなるまで

// All the important information 
String inputFileName = "..."; 
String outputFileName = "..."; 
String lineToRemove = "..."; 
// The traps any possible read/write exceptions which might occur 
try { 
    File inputFile = new File(inputFileName); 
    File outputFile = new File(outputFileName); 
    // Open the reader/writer, this ensure that's encapsulated 
    // in a try-with-resource block, automatically closing 
    // the resources regardless of how the block exists 
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile)); 
      BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { 
     // Read each line from the reader and compare it with 
     // with the line to remove and write if required 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      if (!line.equals(lineToRemove)) { 
       writer.write(line); 
       writer.newLine(); 
      } 
     } 
    } 

    // This is some magic, because of the compounding try blocks 
    // this section will only be called if the above try block 
    // exited without throwing an exception, so we're now safe 
    // to update the input file 

    // If you want two files at the end of his process, don't do 
    // this, this assumes you want to update and replace the 
    // original file 

    // Delete the original file, you might consider renaming it 
    // to some backup file 
    if (inputFile.delete()) { 
     // Rename the output file to the input file 
     if (!outputFile.renameTo(inputFile)) { 
      throw new IOException("Could not rename " + outputFileName + " to " + inputFileName); 
     } 
    } else { 
     throw new IOException("Could not delete original input file " + inputFileName); 
    } 
} catch (IOException ex) { 
    // Handle any exceptions 
    ex.printStackTrace(); 
} 

は、いくつかのより多くのためのBasic I/OThe try-with-resources Statementを見てください詳細

0

コンソールからの入力の読み取り、ファイルの読み取り、ファイルへの書き込みは、区別して別々に行う必要があります。あなたは同時にファイルを読み書きすることはできません。あなたはあなたのファイルを読んでいません。 whileループでコンソール入力を無期限に比較しているだけです。実際には、入力行にlineTobeRemovedを設定することさえありません。それをやり遂げる一つの方法があります。

アルゴリズム:

は、ファイルを読み込むと、あなたの入力ラインと比較することにより、削除する行を探し始めるコンソール入力(削除するかライン)を読みます。行が一致しない場合は、読み込み行を変数に格納します。そうしないと、行を削除したいので、この行をスローします。 読み取りが終了したら、ファイルに保存されている行の書き込みを開始します。これで、1行を削除してファイルを更新しました。

public static void main(String args[]) { 
    String input = "Please delete: "; 
    System.out.println(input); 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       System.in)); 
     String line = reader.readLine(); 
     reader.close(); 

     String inFile = "list.txt"; 


       System.out.println("Remove: " + line); 
       String lineToRemove = line; 


       StringBuffer newContent = new StringBuffer(); 

       BufferedReader br = new BufferedReader(new FileReader(inFile)); 
       while ((line = br.readLine()) != null) { 
        if (!line.trim().equals(lineToRemove)) { 
         newContent.append(line); 
         newContent.append("\n"); // new line 

        } 
       } 
        br.close(); 

       FileWriter removeLine = new FileWriter(inFile); 
       BufferedWriter change = new BufferedWriter(removeLine); 
       PrintWriter replace = new PrintWriter(change); 
       replace.write(newContent.toString()); 
       replace.close(); 

    } 

    catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 
+0

最後の 'if(br.readLine()== null)'テストは無意味です。すでに 'while'ループでnullを返しているので、他のものにすることはできません。そして、魔法のようにnullを返さなかった場合、あなたはそれを投げ捨てて、決して出力を閉じることはありません。 – EJP

+0

@EJPそうです。私はそれを更新する。 – hhafeez

+0

'\ n'はプラットフォーム上で動作しません。 – MadProgrammer

関連する問題