0

コンマと二重引用符で区切られた値を持つ .csv ファイルがあります。

今、コンマ区切りの値を解析したいのですが、二重引用符で囲まれた値がある場合、スキャナーで二重引用符を区切り文字として使用する必要があります。

解析する行の例:

123,student,"試験の通知", "パターンは同じである必要があります,検証済み,適切です"

今、私はそれを次のように解析したい:

123  //comma seperated
student
exam notification   //when "" it should be double quote separated
pattern should be same,validated,proper  //ignore , comma in double quotes

私が試したコード:

scanner.useDelimiter(",|\"");

, と "" の両方を使用できるように、それはうまくいきますが、その間に,"が当たる空白行を出力し、二重引用符の間のコンマを無視することもできません。

それを並べ替える方法はありますか??

4

3 に答える 3

1

OpenCSVのような CSV パーサーを使用して、引用符で囲まれた要素のコンマ、複数行にまたがる値などを自動的に処理します。ライブラリを使用して、テキストを CSV としてシリアル化することもできます。

CSVReader reader = new CSVReader(new FileReader("file.csv"));

String [] nextLine;
// prints the following for the line in your question
while ((nextLine = reader.readNext()) != null) {
    System.out.println(nextLine[0]); // 123
    System.out.println(nextLine[1]); // student
    System.out.println(nextLine[2]); // exam notification
    System.out.println(nextLine[3]); // pattern should be same,validated,proper
}
于 2013-08-21T08:38:45.873 に答える
1

車輪を再発明するのではなく、ここで Super CVS を試してください

http://supercsv.sourceforge.net/examples_reading.html

よろしく

于 2013-08-21T07:46:27.437 に答える
0

やりたいことを実現する方法はいくつかありますが、

1.) Ravi Thapliyal や Oibaf など、CSV の解析をサポートする既存のライブラリを使用してください。

2.) メソッドを提供することができます

         a). if every line in your CSV have a uniform format like : 
            line 1 :  123,student,"exam notif","word , word , word"
            line 2 : 45345,not student,"no exam notif","word,word,word"
   you can say like 

        while(scan.hasNextLine()){
        String line = scan.nextLine();
        //split it using double quotes first
        temp = line.split("\"");
        //then just remove commas outside the double quoted objects
        for(int x = 0; x<temp.length; x++){
            if(temp[x].startsWith(",")) {temp[x] = temp[x].substring(1,temp[x].length()); }
            if(temp[x].endsWith(",")) {temp[x] = temp[x].substring(0,temp[x].length()-1); }
        }

このプログラマに関する限り、Java には複数の区切り文字用の既存のクラスメソッドはありませんが、作業を楽にするライブラリがいくつかありますが、独自のメソッドを提供するオプションが常に与えられます。運がいい

于 2013-08-21T10:22:55.427 に答える