0

我今天断断续续地研究这个。

这是我的方法,它基本上需要接受 .data (txt) 文件位置,然后遍历该文本文件的内容并根据存在的分隔符将其分解为字符串。这是2个文件。个人档案。

Person ID,First Name,Last Name,Street,City
1,Ola,Hansen,Timoteivn,Sandnes

2,Tove,Svendson,Borgvn,Stavanger
3,Kari,Pettersen,Storgt,Stavanger

订单文件。

Order ID|Order Number|Person ID
10|2000|1
11|2001|2
12|2002|1
13|2003|10


public static void openFile(String url) {
        //initialize array for data to be held
        String[][] myStringArray = new String[10][10];
        int row = 0;
        try {
            //open the file
            FileInputStream fstream = new FileInputStream(url);
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                //ignores any blank entries 
                if (!"".equals(strLine)) {
                    //splits by comma(\\| for order) and places individually into array 
                    String[] splitStr = new String[5];
                    //splitStr = strLine.split("\\|");
                    /*
                     * This is the part that i am struggling with getting to work.
                     */

                    if (strLine.contains("\\|")) {
                        splitStr = strLine.split("\\|");
                    } else if (strLine.contains(",")) {
                        splitStr = strLine.split(",");
                    }else{
                        System.out.println("error no delimiter detected");
                    }

                    for (int i = 0; i < splitStr.length; i++) {
                        myStringArray[row][i] = splitStr[i];
                        System.out.println(myStringArray[row][i]);
                    }
                }
            }
            //Close the input stream
            br.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

正确读取和解析人员文件。但是带有“|”的命令文件 分隔符没有它。我只是得到“空”的打印输出。

令我困惑的是,当我只有 splitStr = strLine.split("\|"); 它有效,但我需要这种方法能够检测存在的分隔符,然后应用正确的拆分。

任何帮助都感激不尽

4

1 回答 1

2

Apart from the fact that this should be done using a CSV library, the reason this code is failing is that contains doesnt accept a regular expression. Remove the escape characters so the pipe character can be detected

if (strLine.contains("|")) {
于 2013-09-27T17:47:10.770 回答