2017-01-29 1 views
2

텍스트 파일에서 읽고 쓰는 데 문제가있는 것 같습니다.텍스트 읽기 및 쓰기가 완료되지 않았습니까?

두 개의 서로 다른 파일을 가지고있는 동안 콘텐츠를 인쇄했지만 텍스트 파일에 있어야하는 것과 같지 않습니다.

나는 +와 -를 더하거나 bw.close()를 추가하거나하지 않고 추가하려고 시도했다. 스캐너를 대신 사용하려고했지만 아무 것도 출력하지 못했습니다.

어떻게 든 변경 될 수 있습니까? 당신은 두 번 bw.readLine()를 사용하는

private void readFromFile(File cf2) throws IOException, Exception { 

    FileReader fr = new FileReader(cf2); 
    try (BufferedReader bw = new BufferedReader(fr)) { 
    System.out.println("Wait while reading !"); 

    while(bw.readLine() != null) 
    s1 += bw.readLine(); 
    System.out.println(s1); 
    bw.close(); 
    } System.out.println("File read !"); 
    } 

답변

1

절반 null에 대한 데이터를 확인하기 위해 사용되는보십시오, 나머지 절반은 s1에 추가됩니다. 이것이 입력의 일부분을 얻는 이유입니다.

, 당신의 코드를 수정과 같은 루프를 만들려면 :

while (true) { 
    String s = bw.readLine(); 
    if (s == null) break; 
    s1 += s; 
} 

그러나이 심하게 비효율적입니다. 당신은 StringBuffer를 사용하여 더 나을 것 : 파일에서 '\n' 기호 것도 출력 문자열에있을 것

StringBuffer sb = new StringBuffer() 
while (true) { 
    String s = bw.readLine(); 
    if (s == null) break; 
    sb.append(s); 
    // Uncomment the next line to add separators between lines 
    // sb.append('\n'); 
} 
s1 = sb.toString(); 

참고. 구분 기호를 다시 추가하려면 위 코드에서 주석 처리 된 줄의 주석 처리를 제거하십시오.

+0

StringBuffer와 함께 사용하려고했지만 작동하지 않는 것 같습니다. 그것 없이는 잘 작동합니다. 고맙습니다. –

1

, 마녀는 두 줄을 소비하지만 s1에 그 중 하나마다 추가됩니다. 당신의 readLine 통화의

String line; 
while((line = bw.readLine()) != null) 
    s1 += line; 
System.out.println(s1); 
1

readline()을 두 번 호출하므로 모든 두 번째 줄만 가져옵니다.

private void readFromFile(File cf2) throws IOException, Exception { 

    FileReader fr = new FileReader(cf2); 
    try (BufferedReader br = new BufferedReader(fr)) { 
     System.out.println("Wait while reading !"); 
     StringBuilder sb = new StringBuilder(); 
     String s; 
     while((s = br.readLine()) != null) { 
      sb.append(s); 
     } 
     System.out.println(sb.toString()); 
    } 
    System.out.println("File read !"); 
    } 

당신은이 시도 -과 - 자원에 의해 수행되기 때문에 br을 닫을 필요가 없습니다.