Splitting error- IndexOutOfBoundsException

前端 未结 3 1614
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 23:07

I got stuck with an issue, that I can\'t seem to solve. When splitting I should be able to get id, name, check by setting row[0], row[1], row[2]. Strangely onl

3条回答
  •  既然无缘
    2021-01-24 23:46

    In my experience with txt files this is the best way of dealing with it:

    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.regex.Pattern;
    
    public class Cyto {
    
        public static void main(String[] args) throws IOException {
            ArrayList names = new ArrayList();
            try {
    
                FileInputStream dis = new FileInputStream("list.txt");
                BufferedReader br = new BufferedReader(new InputStreamReader(dis));
                String line;
                while (br.ready()) {
                    line = br.readLine();
                    String[] row = line.split(Pattern.quote(","));      
                    System.out.println(row[1]);
                    names.add(row[1]);
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    

    Use

    br.ready()
    

    instead of reading directly from stream.

提交回复
热议问题