2017-05-14 1 views
1

현재 java.nio.file.File.write(Path, Iterable, Charset)을 사용하여 txt 파일을 작성하고 있습니다. 코드는 ... 여기 .txt 파일에 새 줄 쓰기를 피하십시오.

enter image description here

그러나 텍스트 파일에 생성 한 번 더 (4) 빈 줄

Path filePath = Paths.get("d:\\myFile.txt"); 
    List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine", "3. What about U ?"); 
    Files.write(filePath, lineList, Charset.forName("UTF-8")); 

. 네 번째 빈 줄은 어떻게 피할 수 있습니까?

1 | 1. Hello 
2 | 2. I am Fine 
3 | 3. What about U ? 
4 | 
+0

이럴는, 그것을 생략하는 것보다 종단 줄 바꿈을하는 것이 좋습니다 :

가장 간단한 방법은 당신이 원하는대로 할 수 있습니다. 예를 들어보십시오 http://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline – Henry

+0

아래 좋은 답변을 가지고 있습니다. 감사. @Henry –

답변

1

javadoc에서 작성 : "각 행은 char 시퀀스이며 시스템 등록 정보 line.separator에 정의 된대로 각 행이 플랫폼의 행 분리 자에 의해 종료되는 순서 의 순서로 파일에 기록됩니다."

List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine"); 
String lastLine = "3. What about U ?"; 
Files.write(filePath, lineList, Charset.forName("UTF-8")); 
Files.write(filePath, lastLine.getBytes("UTF-8"), StandardOpenOption.APPEND); 
+0

두 파일을 생성하고 첫 번째 파일 (두 줄 포함)을 마지막 파일 (한 줄)로 바꿉니다. 그리고 마침내 나는 한 줄의 파일 만 얻을 것이다. –

+1

죄송합니다 ... 열린 옵션을 추가하는 것을 잊어 버렸습니다. 결정된. –

+0

예! 이게 내가 원하는거야. 고마워. –

2

확인 Files.write 당신이 전화 코드는 :

writer.newLine(); 

이 솔루션은 다음과 같습니다 : byte[]로 데이터를 제공

public static Path write(Path path, Iterable<? extends CharSequence> lines, 
          Charset cs, OpenOption... options) 
     throws IOException 
    { 
     // ensure lines is not null before opening file 
     Objects.requireNonNull(lines); 
     CharsetEncoder encoder = cs.newEncoder(); 
     OutputStream out = newOutputStream(path, options); 
     try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) { 
      for (CharSequence line: lines) { 
       writer.append(line); 
       writer.newLine(); 
      } 
     } 
     return path; 
    } 

그것은 각 삽입의 끝에서 새로운 라인을 생성 :

Path filePath = Paths.get("/Users/maxim/Appsflyer/projects/DEMOS/myFile.txt"); 
List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine", "3. What about U ?"); 
String lineListStr = String.join("\n", lineList); 
Files.write(filePath, lineListStr.getBytes(Charset.forName("UTF-8"))); 
+0

오! 그렇습니다. 그렇다면 어떻게이 새로운 라인을 피하고 제거 할 수 있습니까? –

+1

@ M.A.Khomeni 그것을 확인하시기 바랍니다, 나는 그것의 더 나은 솔루션이라고 생각합니다. –

+0

예, @ Maxim Shoustin 괜찮습니다. 감사합니다. 하지만 나는 약 500,000 줄에 1100 글자가 너무 많습니다. –

관련 문제