简体   繁体   中英

Reading Files from a list

This is how I have been reading files, If I had a bigger list other than a small grocery list would this way of reading a file still be the most efficient way of opening a file and getting information from it? Lets say I didn't have a grocery list but maybe an Excel file? what changes would be needed?

This grocery list can be as follows (its a .txt file)

Item Price Quantity

Apple 2.99 2

Orange 1.99 1

Juice 4.99 3

Chicken 9.99 1

Milk 2.99 1

Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFiles{

public static void main(String[] args) throws FileNotFoundException {

Scanner g = new Scanner(new File("groceries.txt"));
double sum = 0;

g.nextLine();

while (g.hasNext())
{
    String a = g.nextLine();

    String [] c = a.split(" ");
    String item = c[0];
    double price = Double.parseDouble(c[1]);
    int q = Integer.parseInt(c[2]);

    if(!item.equals("Chicken"))
    {
        sum = sum +(price*q);
    }

}

System.out.println("The total is: "+sum);


}

}

I believe you are reading it correctly if it is a plain text file. But if you have an excel To use Apache POI, which provides certain easy-to-use APIs. Here is the reference URL for the same:

http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/

If you have control or decision with you about which file you can use to store the grocery data then csv can also be a good choice. Here is another link to help you with csv reading:

http://viralpatel.net/blogs/java-read-write-csv-file/

Choose wisely, hope it helps!

If the file you need to read would be an Excel file you'd probably want to use one of the existing API's that exist to read Java files. The most well-known choices are:

  • jExcelAPI which is rather lightweight and tends to consume less memory when working with big files, but is limited to reading and writing .xls (Excel 2003 and earlier) files. As the author's website seems down right now, there a nice short example here that shows how easy it is to read an xls file.
  • Apache POI HSSF/XSSF , the more sophisticated option that can also handle .xlsx files (Excel 2007 and later), but at the cost of a much higher memory consumption and an API that's a bit harder to learn.

A nice way to read in structured text files I've working with lately is jsapar , it allows you to parse a file like your directly into a Java List. I'm not claiming that it will be faster than raw reading, but it can be quite helpful nevertheless.

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