繁体   English   中英

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

[英]Reading file (using FileReader) and splitting line into two strings in 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 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[] 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词典链接。

您的字典文件不是您的程序所期望的。

有带有单个字母的行(就像包含单个字母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);
    }
}  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM