2017-10-19 4 views
-1
import java.io.*; 


public class ReadFile { 

public static void read(File f) throws IOException { 
    //String delimiters = "."; 
    FileReader fr = new FileReader(f); 

    BufferedReader br = new BufferedReader(fr); 

    String line; 
    //int numberOfLines = 0; 
    while ((line = br.readLine()) != null) { 
     String[] tokens = line.split("\\.", 2); 
     String p1 = tokens[0]; 
     String p2 = tokens[1]; 
     System.out.println(p1); 
     System.out.println(p2); 
     //numberOfLines++; 
    } 
    //System.out.println("Numebr of lines in file: " + numberOfLines); 
    br.close(); 
    fr.close(); 

} 

public static void main(String[] args) { 
    File f = new File("F:\\Dictionary.txt"); 
    try { 
     read(f); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 

} 


} 

私は辞書をテキストファイルとして使用していますが、辞書ファイルの行を読みたい私は "単語"とその "意味"を別の配列インデックスに格納できるように分割します。このString[] tokens = line.split("\\.", 2); to read and split at only the first "." (so that words proceeding after "." will be splitted!). I seem to having an error of ArrayIndexOutOfBound and I don't know why. I want文字列p1 =トークン[0]。単語と `String p12 = tokens 1;を格納します。言葉の意味どうしたらいいですか? ​​辞書のリンク。ファイルを読み込み(FileReaderを使用)、Javaの2つの文字列に分割する

答えて

0

あなたの辞書ファイルはあなたのプログラムが期待しているものではありません。

一文字の行があります(最初の行は一文字のAです)。それから、空の行がたくさんあります。

あなたの処理をより堅牢にするためには、あなたの構文解析ループにこれらの変更を行います。

while ((line = br.readLine()) != null) { 
    //skip empty lines 
    if (line.length() <= 1) { 
     continue; 
    } 
    try { 
     String[] tokens = line.split("\\.", 2); 
     String p1 = tokens[0]; 
     String p2 = tokens[1]; 
     System.out.println(p1); 
     System.out.println(p2); 
    } catch (IndexOutOfBoundsException e) { 
     //catch index out of bounds and see why 
     System.out.println("PROBLEM with line: " + line); 
    } 
} 
関連する問題