2017-11-19 3 views
1

안녕하세요, 저는 각 코드를 읽고 각 줄마다 문자열에 저장하는 데 어려움을 겪고 있습니다. 내 코드는 아래 텍스트 파일을로드 할 수 있지만 그것을 분할 할 수 없습니다, 나는 첫 번째 줄 나누기 얻을 수 및 그 것입니다. 나는 자바가 훌륭하지 않지만 4 줄짜리 텍스트 파일을로드하려고하고 있는데 그 코드를 파일에서 다른 문자열로 분할해야한다. 첫 번째 코드 줄을 가져올 수는 있지만 그게 전부입니다.Java : 파일을 각 행에 대한 문자열로 분할 하시겠습니까?

Load.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 

      JFileChooser fileChooser = new JFileChooser(); 

      int returnValue = fileChooser.showOpenDialog(null); 

      if (returnValue == JFileChooser.APPROVE_OPTION) { 


       File file = fileChooser.getSelectedFile(); 

       try { 

        BufferedReader reader = new BufferedReader(new FileReader(file)); 


        String nextLine = reader.readLine(); 


        if (nextLine != null && nextLine.startsWith("Title:")) { 

         title = nextLine.substring(6); 

         panel.showText(title); 
         nextLine = reader.readLine(); 
        } 


        reader.close(); 
       } catch (IOException e1) { 

        System.err.println("Error while reading the file"); 
       } 
      } 


     } 
    }); 

답변

0
while(nextLine != null){ 
    if (nextLine != null && nextLine.startsWith("Title:")) { 
     title = nextLine.substring(6); 
     panel.showText(title); 
     nextLine = reader.readLine(); 
    } 
} 
reader.close(); 

+0

가 왜 꽵 두 번 확인합니다! = 여기서 코드 자체보다 더 while 루프를 추가하는 강조 – Christian

+0

널, 내가하는 방법으로이 문제를 유출 한 것입니다있는이해야 아마도 – dave

2

나는 아래 https://kodejava.org/how-do-i-read-text-file-content-line-by-line-using-commons-io/ 유용 할 수있다 생각해야한다.

이것은 아파치 공유의 FileUtils를 제안합니다. 위의 사이트에서 복사했습니다. 내가 정말 그것에 의해 방해 한 경우

File file = new File("sample.txt"); 

     try { 
      List<String> contents = FileUtils.readLines(file); 

      // Iterate the result to print each line of the file. 
      for (String line : contents) { 
       System.out.println(line); 
      } 
     } 
+0

링크의 내용이 나중에 변경되면 여기에 대한 답변이 나빠질 수 있으므로 해당 링크의 관련 세부 정보를 여기에 추가하십시오. –

관련 문제