2017-10-26 1 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 속성을 추가하면 추가되지만 출력은 단일 행으로 작성됩니다. 내 질문은, 내가 그 형식 그래서 뭔가 잘못하고있는 중이 야한다

<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

감사합니다'를 사용하고 있기 때문에 당신은/작가를하여, 독자를 종료 할 필요가 없습니다. 습관의 힘 :) –

+0

모든 것이 한 줄로 작성 되었습니까? 아니면 그냥 몇 줄? – Lino

답변

1

문제를 해결하려면 쓰기를 원하는 모든 줄에 라인 구분 기호 (\n)를 추가하기 만하면됩니다.

그래서이 : writeToFile.add(readLine);이된다 : writeToFile.add(readLine+"\n");

+0

감사합니다 Lino. 그게 문제를 해결 :) –