读取文件(使用FileReader)并在Java中将行拆分为两个字符串

时间:2017-10-19 16:06:23

标签: java filereader

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();
    }

}


}

我有一个问题,我使用字典作为文本文件,我想读取(字典文件)的行,然后将其拆分,以便我可以存储"单词&# 34;和他们的意思"进入不同的数组索引。这个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 String p1 = tokens [0];存储单词和`String p12 = tokens 1;这些词的含义。我该怎么做? https://drive.google.com/open?id=0ByAbzVqaUg0BSFp5NXNHOGhuOFk字典链接。

1 个答案:

答案 0 :(得分: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);
    }
}  
相关问题