2010-06-04 8 views
8

안녕하세요, N 행의 txt 파일을 읽고 결과를 문자열 배열에 넣으려고합니다.java : txt 파일을 문자열 배열로 읽는 방법

+3

이제 우리는 당신이 원하는 것을 알고 있습니다. 당신의 질문은 무엇입니까? :) – OscarRyz

+1

여기에 몇 가지 대안 (그들은 단지 약간의 조정이 필요합니다) http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file – OscarRyz

+0

그리고 또 다른 : http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html – OscarRyz

답변

21

java.util.Scannerjava.util.List을 사용하십시오.

Scanner sc = new Scanner(new File(filename)); 
List<String> lines = new ArrayList<String>(); 
while (sc.hasNextLine()) { 
    lines.add(sc.nextLine()); 
} 

String[] arr = lines.toArray(new String[0]); 
+1

이있는 대답, 감사 남자 : –

+3

@Enrique! 어떻게'스캐너에 대한 API를 읽어 'IOException'을 처리합니다. – polygenelubricants

+0

String [] arr의 모든 요소를 ​​인쇄하는 방법? – Chinmoy

3

the Java tutorial을 읽으셨습니까? 예를 들어

:

Path file = ...; 
InputStream in = null; 
try { 
    in = file.newInputStream(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
     System.out.println(line); 
    } 
} catch (IOException x) { 
    System.err.println(x); 
} finally { 
    if (in != null) in.close(); 
} 
+1

그래, 내가 자바 튜토리얼 및 기타 도서를 읽고,이 문제를 해결하지 않기 때문에 나는 모든 라인을 넣으려면 문자열의 배열에있는 파일은 다음과 같습니다. String [] content = new String [lenght_of_the_string]; int i = 0; 동안 ((라인 = reader.readLine()) = 널 (null) { 내용 [I] = 라인; 내가 ++; } –

5
FileUtils.readLines(new File("/path/filename")); 

apache commons-io에서이 당신에게 StringList을 얻을 것이다. List.toArray()을 사용하여 변환 할 수 있지만 List으로 머무를 것을 권합니다.

0

파일에서 읽을 수 있도록 BufferedReader을 설정 한 다음 버퍼에서 여러 줄을 여러 번 가져옵니다.

관련 문제