【问题标题】:Reading file (using FileReader) and splitting line into two strings in Java读取文件(使用 FileReader)并将行拆分为 Java 中的两个字符串
【发布时间】:2017-10-19 16:06:23
【问题描述】:
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 wantString p1 = tokens[0];存储单词和`String p12 = tokens1;单词的含义。我该怎么做? https://drive.google.com/open?id=0ByAbzVqaUg0BSFp5NXNHOGhuOFk 字典链接。

【问题讨论】:

    标签: java filereader


    【解决方案1】:

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

    有些行带有单个字母(例如第一行包含单个字母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);
        }
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      相关资源
      最近更新 更多