2017-10-26 6 views
2

ファイルを読み込み、いくつかの基準に基づいて同じファイルにテキストを追加します。これは私のコードです。同じファイルを読み書きします - 出力形式の変更

public static void writeOutputToFile(ArrayList<String> matchingCriteria) { 

    //Provide the folder which contains the files 
    final File folder = new File("folder_location"); 
    ArrayList<String> writeToFile = new ArrayList<String>(); 

    //For each file in the folder 
    for (final File fileEntry : folder.listFiles()) { 

     try (BufferedReader br = new BufferedReader(new FileReader(fileEntry))) { 
      String readLine = ""; 

      while ((readLine = br.readLine()) != null) { 
       writeToFile.add(readLine); 
      } 

      try (FileWriter fw = new FileWriter(fileEntry); BufferedWriter bw = new BufferedWriter(fw)) { 
       for (String s : writeToFile) { 
        boolean prefixValidation = false; 
        //Check whether each line contains one of the matching criterias. If so, set the condition to true 
        for (String y : matchingCriteria) { 
         if (matchingCriteria.contains(y)) { 
          prefixValidation = true; 
          break; 
         } 
        } 
        //Check if the prefixes available in the string 
        if (prefixValidation) { 
         if (s.contains("name=\"") && !(s.contains("id=\""))) { 
          //Split the filtered string by ' name=" ' 
          String s1[] = s.split("name=\""); 

          /*Some Code*/       
          //Set the final output string to be written to the file 
          String output = "Output_By_Some_Code"; 

          //Write the output to the file. 
          fw.write(output); 

//If this action has been performed, avoid duplicate entries to the file by continuing the for loop instead of going through to the final steps 
           continue; 
          } 
         } 
         fw.write(s); 
         bw.newLine(); 
        }    
        fw.flush(); 
        bw.flush(); 
//Clear the arraylist which contains the current file data to store new file data. 
         writeToFile.clear(); 
        } 
       } catch (IOException ioe) { 
        ioe.printStackTrace(); 
       } 
      } 
    } 

このコードは正常に動作します。問題は、出力が入力ファイルとまったく同じではないということです。入力ファイル内のいくつかのコンテンツを追加する複数の行は、出力ファイルの同じ行に書き込まれます。

たとえば、これらの要素にid属性を追加して追加しますが、出力は1行で記述されます。

<input type="submit" <%=WebConstants.HTML_BTN_SUBMIT%> value="Submit" /> 
<input type="hidden" name="Page" value="<%=sAction%>" /> 
<input type="hidden" name="FileId" value="" /> 

フォーマットが台無しになっているように、私の質問は、私が何か間違ったことをやっているのですか?
もしそうなら、入力ファイルとして正確に印刷するための何かがありますか?

助けていただきありがとうございます。ありがとうございます。

+0

ませんが、あなたは、 'てみ-で-resources'-ステートメント – Lino

+0

感謝を使用しているので、あなたは、あなたの、リーダ/ライタをクローズする必要はありません。writeToFile.add(readLine);このなります。習慣の力:) –

+0

すべてが1行に書かれていますか?またはいくつかの行? – Lino

答えて

1

問題を解決するには、書きたいすべての行に改行記号(\n)を追加してください。

ので、この:修正writeToFile.add(readLine+"\n");

+0

ありがとうLino。それは問題を解決した:) –

関連する問題