阅读文件(使用FileReader)和分裂成两个字符串的Java
问题描述:
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 =令牌1;这些词的意思。我该怎么做? Link for Dictionary。阅读文件(使用FileReader)和分裂成两个字符串的Java
答
你的字典文件不是你的程序所期望的。
有单行的行(比如第一行包含单个字母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);
}
}