2016-06-15 2 views
1

내가 .txt 파일에서 읽고 싶은 발생하면 저장,하지만 난 빈 줄이 발생하는 경우 예를 들어, 각 문자열을 저장하려면 :는 - 라인 - 휴식

All 
Of 
This 
Is 
One 
String 

But 
Here 
Is A 
Second One 

모든 단어에서 All ~ String은 하나의 문자열로 저장되고 But의 모든 단어는 다른 문자열로 저장됩니다. 이것은 현재 코드입니다 :

public static String getFile(String namn) { 
    String userHomeFolder = System.getProperty("user.home"); 
    String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt"; 
    int counter = 0; 
    Scanner inFil = new Scanner(new File(filnamn)); 
    while (inFil.hasNext()) { 
     String fråga = inFil.next(); 
     question.add(fråga); 
    } 
    inFil.close(); 

} 

어떻게 조정해야합니까? 현재는 각 행을 단일 문자열로 저장합니다. 미리 감사드립니다.

+0

이것은 좋은 질문이며 사용하는 언어에 대한 태그를 추가하면 더 많은 의견을 얻을 수 있습니다. – Matthew

답변

1

귀하의 질문은 java와 관련 있다고 가정합니다.
전체 텍스트를 여러 문자열로 분할 할 때 단일 문자열을 반환하는 것이 의미가 없기 때문에 메서드의 반환 형식을 List로 변경했습니다.
또한 question 변수를 알지 못하므로 allParts 문장을 빈 줄 (변수 part)으로 구분하여 전환했습니다.

public static List<String> getFile(String namn) throws FileNotFoundException { 
    String userHomeFolder = System.getProperty("user.home"); 
    String filnamn = userHomeFolder + "/Desktop/" + namn + ".txt"; 
    int counter = 0; 

    // this list will keep all sentence 
    List<String> allParts = new ArrayList<String>(); s 

    Scanner inFil = new Scanner(new File(filnamn)); 

    // part keeps single sentence temporarily 
    String part = ""; 
    while (inFil.hasNextLine()) { 
     String fråga = inFil.nextLine(); //reads next line 
     if(!fråga.equals("")) {  // if line is not empty then 
       part += " " + fråga;  // add it to current sentence 
      } else {     // else  
       allParts.add(part);  // save current sentence 
       part = "";    // clear temporary sentence 
      } 

     } 
     inFil.close(); 
     return allParts; 

    } 
+0

도움을 많이 주셔서 감사합니다! – Playdowin