Splitting error- IndexOutOfBoundsException

前端 未结 3 1589
没有蜡笔的小新
没有蜡笔的小新 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:43

    Probably in the time:

    String[] row = line.split(",");
    

    was called, there was no comma (,) in the line of the file/stream you're trying to read.

    0 讨论(0)
  • 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<String> names = new ArrayList<String>();
            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.

    0 讨论(0)
  • 2021-01-24 23:47

    Try this code,

    ArrayList<String> names = new ArrayList<String>();
        try {
    
            DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
            BufferedReader br = new BufferedReader(new InputStreamReader(dis));
            String line;
            while ((line = br.readLine()) != null) {
                String[] row = line.split(",");
                //names.add(row[0]); // id
                names.add(row[1]); // name // ERROR AT THIS LINE
                //names.add(row[2]); // check
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    

    I think you don't need to use Pattern.quote(",") here.

    0 讨论(0)
提交回复
热议问题