簡體   English   中英

如何在 Java 上獲得正確的逗號分割字符串?

[英]How can I get a correct string split by coma on Java?

我有下一個 csv 文件:

hotel,is_canceled,lead_time, ..
Resort Hotel,0,300, ..
Resort Hotel,0,

例如,當我想要一個帶有第一列的 ArrayList 時,問題就來了:

[Resort Hotel, Resort Hotel, .. ]

為此,我逐行讀取文件,在每一行(它是整個字符串行)上,我使用 row.split(",")。 但是我這樣做的結果是這樣的: [Resort, Hotel, Resort, Hotel, ...]當我想要[Resort Hotel, Resort Hotel, ...]我嘗試使用 split("\," ) 和 split(Pattern.quote(",")) 但這些都不起作用。 不知道為什么它在有空格時也會拆分數據,而不僅僅是昏迷。

任何想法? 我會把代碼放在這里,以防我的代碼出錯。 我首先要做的是使用掃描儀讀取文件,然后(在第一次)我搜索一個具體屬性(在本例中為酒店),然后在第二次我逐行將行拆分為昏迷並抓住我想要的一個屬性,將其添加到結果數組中。

public String[] read_column_scan(String file, String atribut) {
    File _file = new File(file);
    try {
        Scanner inputStream = new Scanner(_file);
        String data;
        data = inputStream.next();
        String[] values = data.split(",");
        boolean found = false;
        int i = -1;
        while(!found && (i < values.length)) {
            ++i;
            if(values[i].equals(atribut)) found = true;
        }
        ArrayList<String> result_aux = new ArrayList<String>();
        String[] values2;
        while(inputStream.hasNext()) {
            data = inputStream.next();
            values2 = data.split(",");
            String aux = values2[i];
            result_aux.add(aux);
        }
        String[] result = new String[result_aux.size()];
        result_aux.toArray(result);
        return result;
    } catch(Exception e) {
        e.printStackTrace();
    }
    return null;
}

class Scanner中的方法next()讀取下一個標記,標記的默認分隔符是空格。 您希望Scanner讀取 CSV 文件的整行。 因此,您需要方法hasNextLIne()來查看文件中是否還有另一行,並需要方法nextLine()來讀取整行。 然后您的split(",")將起作用,因為您的字符串是一整行而不僅僅是一個單詞。

public String[] read_column_scan(String file, String atribut) {
    File _file = new File(file);
    try {
        Scanner inputStream = new Scanner(_file);
        String data;
        data = inputStream.nextLine(); // change here
        String[] values = data.split(",");
        boolean found = false;
        int i = -1;
        while(!found && (i < values.length)) {
            ++i;
            if(values[i].equals(atribut)) found = true;
        }
        ArrayList<String> result_aux = new ArrayList<String>();
        String[] values2;
        while(inputStream.hasNextLine()) { // change here
            data = inputStream.nextLine(); // change here
            values2 = data.split(",");
            String aux = values2[i];
            result_aux.add(aux);
        }
        String[] result = new String[result_aux.size()];
        result_aux.toArray(result);
        return result;
    } catch(Exception e) {
        e.printStackTrace();
    }
    return null;
}

如果您使用 CSV 解析器庫而不是嘗試自己解析它,您將為自己省去很多痛苦。 您已經錯過了對引用值的正確處理。

我推薦使用 OpenCSV http://opencsv.sourceforge.net/#even_quicker_start

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM