简体   繁体   中英

reading from a comma separated text file

I am trying to write a Java program that simulates a record store shopping cart. The first step is to open up the inventory.txt file and read the contents which is basically what the " store has to offer ". Then I need to read every line individually and process the id record and price.

The current method outputs a result that is very close to what I need, however, it picks up on the item id of the next line, as you can see below.

I was wondering if someone can assist me in figuring out how to process every line in the text document individually and store every piece of data in its own variable without picking up the id of the next item?

public void openFile(){
    try{
        x = new Scanner(new File("inventory.txt"));
        x.useDelimiter(",");
    }
    catch(Exception e){
        System.out.println("Could not find file");
    }
}

public void readFile(){
    while(x.hasNext()){
        String id = x.next();
        String record = x.next();
        String price = x.next();            
        System.out.println(id + " " + record + " " + price);
        break;
    }
}

.txt document:

11111, "Hush Hush... - Pussycat Dolls", 12.95
22222, "Animal - Ke$ha", 9.95
33333, "Hanging By A Moment - Lifehouse - Single, 4.95
44444, "Have A Nice Day - Bon Jovi", 9.99
55555, "Day & Age - Killers", 10.99
66666, "She Wolf - Shakira", 15.99
77777, "Dark Horse - Nickelback", 12.99
88888, "The E.N.D. - Black Eyed Peas", 10.95

actual output

11111  "Hush Hush... - Pussycat Dolls"  12.95
22222

expected result

11111  "Hush Hush... - Pussycat Dolls"  12.95

So the problem here specifically is that you are breaking on commas, and you should be breaking on commas and newlines. But there are tons of other corner cases (for example, if your column is "abc,,,abc" you shouldn't break on those commas). Apache Commons comes with a CSVParser that handles all of these corner cases, you should use it:

http://commons.apache.org/csv/apidocs/org/apache/commons/csv/CSVParser.html

You can use a Pattern as the argument to Scanner.useDelimiter . Use this to provide alernates for the delimiter: either comma, or the line separator.

x.useDelimiter(",|" + System.getProperty("line.separator"));

Depending on what your input file uses as the line separator, you may need to change the second option.

The advice in other answers to use an existing CSV library is good: parsing CSV isn't as simple as breaking up the input around commas.

有多种方法可以实现此目的,但是按照您自己的方式,您可以使用Scanner首先读取行(使用Java的“ line.separator”作为定界符),然后再次使用Scanner类并将逗号作为定界符。

The problem you're going to be facing is the CSV is more then just splitting a String on a comma. There are considerations to take into account with "escaped" commas (commas you don't want to delimante against).

I suggest you save your self a lot of time and head aches and use an existing API.

The Apache Commons has already been mentioned. I recently used OpenCSV and found it to be extremely simple to use and powerful

IMHO

An easy way to read in the entire file into a list of Strings (lines)...

public class Scanner {
public static List<String> readLines(String filename) throws IOException {
    FileReader fileReader = new FileReader(filename);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    List<String> lines = new ArrayList<String>();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
    bufferedReader.close();
    return lines;
  }
}

Then you can process the individual lines as before, as each line is it's own String object. That is, if you don't use a CSVParser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM