2017-05-03 9 views
1

내 방법이 파일을 읽고 인쇄하지만 각 단어를 ArrayList dict에 추가하는 데 문제가 있습니다.텍스트 파일 읽기 (~ 90,000 단어) 각 단어를 문자열의 ArrayList에 추가하려고합니다.

독자가 파일을 한 번에 하나씩 읽으므로 작성자가 각 문자를 dict에 추가합니다. [고양이, 개]를 원할 때 [c, a, t, d, o, g]. 텍스트 파일에는 단어가 각 행에 있습니다. 어떻게 구별 할 수 있습니까? 지금까지

내 코드 :

public static List Dictionary() { 
    ArrayList <String> dict = new ArrayList <String>(); 

    File inFile = new File("C:/Users/Aidan/Desktop/fua.txt"); 
    FileReader ins = null; 

    try { 
     ins = new FileReader(inFile); 

     int ch; 

     while ((ch = ins.read()) != -1) { 
      System.out.print((char) ch); 

      dict.add((char) ch + ""); 
     } 
    } catch (Exception e) { 
     System.out.println(e); 
    } finally { 
     try { 
      ins.close(); 
     } catch (Exception e) { 
     } 
    } 
    return dict; 
} 
+0

이 문제를 해결하기위한 좋은 예와 접근법이 있다고 가정합니다. 다음 [post] (https://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/)를 참조하십시오. –

답변

0

(클래스 이름처럼 보임) 대신 readDictionary 이니 Java 명명 규칙을 준수하십시오. 그런 다음 메서드에 경로를 하드 코딩하는 대신 fileName을 메서드에 전달합니다. 휠을 재발 명하는 대신 Scanner을 사용합니다. 여기 finally (및 다이아몬드 연산자) 대신 try-with-resources을 사용할 수도 있습니다. 마찬가지로,

public static List<String> readDictionary(String fileName) { 
    List<String> dict = new ArrayList<>(); 

    try (Scanner scan = new Scanner(new File(fileName))) { 
     while (scan.hasNext()) { 
      dict.add(scan.next()); 
     } 
    } catch (Exception e) { 
     System.out.printf("Caught Exception: %s%n", e.getMessage()); 
     e.printStackTrace(); 
    } 
    return dict; 
} 

는 또한하는 BufferedReadersplit 각 단어를 직접 사용합니다. 마찬가지로,

public static List<String> readDictionary(String fileName) { 
    List<String> dict = new ArrayList<>(); 

    try (BufferedReader br = new BufferedReader(new FileReader(
       new File(fileName)))) { 
     String line; 
     while ((line = br.readLine()) != null) { 
      if (!line.isEmpty()) { 
       Stream.of(line.split("\\s+")) 
         .forEachOrdered(word -> dict.add(word)); 
      } 
     } 
    } catch (Exception e) { 
     System.out.printf("Caught Exception: %s%n", e.getMessage()); 
     e.printStackTrace(); 
    } 
    return dict; 
} 

하지만 기본적으로 첫 번째 예에서와 같습니다.

0

체크 아웃 파일에서 단어를 얻기 위해 스캐너를 사용하는 방법을 보여줍니다 여기에 답 : Read next word in java.

단어를 인쇄하는 대신 ArrayList에 단어를 추가 할 수 있습니다.

0
한 번에 하나의 문자를 읽을 수 FileReaderread 방법으로

하고 당신이 원하는, 나는 당신이 파일을 읽을 수있는 Scanner를 사용하는 것이 좋습니다 것입니다하지입니다.

ArrayList<String> dict = new ArrayList<>(); 
Scanner scanner = new Scanner(new File("C:/Users/Aidan/Desktop/fua.txt")); 
while(scanner.hasNext()){ 
    dict.add(scanner.next()); 
} 
0

당신은 포장 할 수 있습니다 당신에게 한 번에 전체 라인 (단어)를 얻을 것이다 readLine() 방법이있는 BufferedReader에서 FileReader. readLine()은 읽을 행이 더 이상 없을 때 null을 반환합니다.