有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java读取一个由tab分隔的文件,并将单词放入ArrayList中

我正在做一个自学练习,以帮助我更多地了解Java,但我被这个问题困住了。我有以下txt文件:

Name  Hobby 
Susy  eat fish 
Anna  gardening
Billy bowling with friends

注:姓名和爱好用制表符隔开

阅读所有行并将其放入arraylist(姓名、爱好)的最佳方式是什么。棘手的是

eat fish or bowling with friends

有空格,必须放在一个数组下,显然我不能硬编码。以下是我目前的代码:

 public void openFile(){
            try{
                FileInputStream fstream = new    FileInputStream("textfile.txt");
          // use DataInputStream to read binary NOT text
          BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
          ArrayList<String> names = new ArrayList<String>();
          ArrayList<String> hobbies = new ArrayList<String>();
          String lineJustFetched;
          while ((lineJustFetched = br.readLine()) != null)   {
          String[] tokens = lineJustFetched.split(" \t");

我有个错误:

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

我怀疑在标签上计算索引不是很有用。 知道吗


共 (2) 个答案

  1. # 1 楼答案

    如果用tab \t分隔了Name和Hobby列,那么应该这样做(不要忘记在末尾关闭scan):

    public void readFile() throws FileNotFoundException{
        Scanner scan = new Scanner(new File("D://a.txt"));
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<String> hobbies = new ArrayList<String>();
    
        while(scan.hasNext()){
            String curLine = scan.nextLine();
            String[] splitted = curLine.split("\t");
            String name = splitted[0].trim();
            String hobby = splitted[1].trim();
            if(!"Name".equals(name)){
                names.add(name);
            }
            if(!"Hobby".equals(hobby)){
                hobbies.add(hobby);
            }
        }
        System.out.println(names);
        System.out.println(hobbies);
        scan.close();
    }
    
  2. # 2 楼答案

    你应该试试commons-lang library。在许多其他有用的东西中,您可以使用分隔符拆分字符串:

    String x="Billy bowling with friends";
    
    String y[]=StringUtils.split(x, '\t');
    

    假设在Billybowling之间有一个制表符

    • y[0]包含“比利”
    • y1包含“与朋友打保龄球”