2016-07-15 2 views
0

내 코드를 모듈화하려고합니다. 제 질문은 일단 getFile 메서드를 호출하여 입력을 얻으면 배열 등을 말하기 위해 어떻게 저장할 수 있습니까?스캐너 클래스 더 모듈화

더 명확히하려면 getFileScanner 메서드를 호출 할 수 있어야하며 사용자가 입력 한 파일의 내용을 반환해야합니다. 그런 다음 main 메소드 내에서 그 입력 (.txt 파일에 있던 모든 것)을 배열 (쓰려면)로 설정할 수 있기를 원합니다. main 메소드에서 입력을 저장하는 방법은 무엇입니까? 이 게시물과는 별도의 다른 게시물에서 사용자는 제 코드를 모듈화하고 다음 코드 중 일부를 제안했습니다. 나는 사용자가 의도 한 것을 이해하고 일부 코드를 분리하려고 노력하고있다.

import java.io.File ; 
import java.io.FileNotFoundException ; 
import java.util.Scanner ; 

public class scanTest { 

    public static void main(String[] args) throws FileNotFoundException { 

     System.out.println("Please enter the file"); 
     System.out.println(getFileScanner()); 

    } 

    public static Scanner getFileScanner() throws FileNotFoundException { 

     Scanner user_input = new Scanner(System.in); 
     String filepath = user_input.next(); 

     System.out.println("Filepath read: " + filepath); 
     // Read input file 
     Scanner input = new Scanner(new File(filepath)); 
     System.out.println(input); 
     return input; 
    } 

} 
+0

질문이나 프로그램에서 무엇을 하려는지 명확하지 않습니다. 당신은 stdin을위한'Scanner'를 만들고, 입력으로부터'String'을 읽고, 그것을 경로로 해석하고,'File'을 열고, 그 파일을위한 새로운'Scanner '를 만들고, 스캐너 객체를 인쇄합니다 (두번) . 사랑을 원하지만, 아직 성취하고자하는 바가 무엇인지 실마리가 없습니다. – AJNeufeld

+0

여기에서 해결책을 찾을 수 있습니다. http://stackoverflow.com/questions/13185727/reading-a-txt-file-using-scanner-class-in-java –

+0

@AJNeufeld이 (가) 내 게시물을 편집했습니다. 의견을 보내 주셔서 감사합니다. – cfsprod

답변

0

코드를 모듈화하는 것은 코드를 작고 자체 포함 된 재사용 가능한 부분으로 분해하는 것을 의미합니다. 다음과 같음 :

public class ScanTest { 
    public static void main(String []args) throws FileNotFoundException { 
     Scanner user_input = new Scanner(System.in); 
     String filepath = getFilePath(user_input); 
     String[] all_lines = readAllLines(filepath); 
    } 

    public static String getFilePath(Scanner user_input) { 
     String filepath = user_input.next(); 
     System.out.println("Filepath read: " + filepath); 
     return filepath; 
    } 

    public static String[] readAllLines(String filepath) throws FileNotFoundException { 
     // TODO: implement 
    } 
} 

이 방법은 좀 더 "모듈 식"입니다. 각 방법은 잘 정의 된 것을 수행합니다.

하지만 질문은 실제로 "파일을 배열로 읽는 방법"입니다.

public static String[] readAllLines(String filepath) throws IOException { 
     List<String> lines = Files.readAllLines(Paths.get(filepath), StandardCharsets.UTF_8); 
     return lines.toArray(new String[list.size()]); 
    }