Read data from a text file and create an object

為{幸葍}努か 提交于 2019-11-30 07:45:11

This is a good job for a Scanner to read in the data. As far as not being able to use collections like ArrayList you'll have to dynamically reallocate an array yourself.

Try the following:

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("Stock.txt"));
    input.useDelimiter("-|\n");

    Product[] products = new Product[0];
    while(input.hasNext()) {
        int id = input.nextInt();
        String department = input.next();
        String name = input.next();
        double price = Double.valueOf(input.next().substring(1));
        int stock = input.nextInt();

        Product newProduct = new Product(name, price, department, id, stock);
        products = addProduct(products, newProduct);
    }

    for (Product product : products) {
        System.out.println(product);
    }
}

private static Product[] addProduct(Product[] products, Product productToAdd) {
    Product[] newProducts = new Product[products.length + 1];
    System.arraycopy(products, 0, newProducts, 0, products.length);
    newProducts[newProducts.length - 1] = productToAdd;

    return newProducts;
}

public static class Product {
    protected String name;
    protected double price;
    protected String department;
    protected int id;
    protected int stock;

    private static NumberFormat formatter = new DecimalFormat("#0.00");

    public Product(String n, double p, String d, int i, int s) {
        name = n;
        price = p;
        department = d;
        id = i;
        stock = s;
    }

    @Override
    public String toString() {
        return String.format("ID: %d\r\nDepartment: %s\r\nName: %s\r\nPrice: %s\r\nStock: %d\r\n", 
                id, department, name, formatter.format(price), stock);
    }
}

Results:

ID: 0
Department: Bakery
Name: Chocolate Cake
Price: 12.50
Stock: 250

ID: 1
Department: Meat
Name: Premium Steak
Price: 2.60
Stock: 120

ID: 2
Department: Seafood
Name: Tuna
Price: 1.20
Stock: 14

For simplicity, I have defined all the items as String.

Product DAO:

public class Product {

    private String name;
    private String price;
    private String department;
    private String id;
    private String stock;

    //generate `enter code here`
    //getters & setters
    //toString

Put your product list in "testData/product.txt". This is assuming that your list of products comes in same format, i.e. id-department-name-price-stock \n.

Use the jUnit test below to test your code. You can certainly modify how you read the product.txt file (may be other powerful string readers).

@Test
    public void test() {

        try {
            List<String> productLines = Files.readAllLines(java.nio.file.Paths.get("./testData/product.txt"), StandardCharsets.UTF_8);

            for (String line: productLines)
Product product = new Product();
                String[] tokens = line.split("-");

                product.setId(tokens[0]);
                product.setDepartment(tokens[1]);
                product.setName(tokens[2]);
                product.setPrice(tokens[3]);
                product.setStock(tokens[4]);

System.out.println(product.toString())
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    } 

For future readers.

I had double quotes surrounding my csv (comma separated values) file. And had some doubles and ints.

I also has going nuts trying to find a "bad line" and the value that was barfing.... in the csv file. Thus my exception with a decent message.

My "delimiter" is a comma and carriage return. And I deal with the double quotes "at the column level".

Here is what I came up with.

 /* I know, a java example with the imports listed out !   shocking !! */
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

private void loadFromFile() {

    Collection<MyCustomObject> items = new ArrayList<MyCustomObject>();
    int lineNumber = 0;
    String nextValue  = "";
    try {

        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource("MyFile.txt").getFile());
        Scanner input = new Scanner(file)
                .useDelimiter(",|\\R")
                .useLocale(Locale.ENGLISH);
        ;

        /* skip the header */
        input.nextLine();

        while (input.hasNext()) {
            lineNumber++;
            nextValue = input.next().replace("\"", "");
            String zipCodeValue =nextValue;

            nextValue = input.next().replace("\"", "");
            String city = nextValue;

            nextValue = input.next().replace("\"", "");
            String usaState = nextValue;

            nextValue = input.next().replace("\"", "");
            double latitude = Double.valueOf(nextValue);

            nextValue = input.next().replace("\"", "");
            double longitude = Double.valueOf(nextValue);

            nextValue = input.next().replace("\"", "");
            int population = Integer.valueOf(nextValue);

            items.add(new MyCustomObject(zipCodeValue, city, usaState, latitude, longitude, population));
        }
    } catch (Exception ex) {
        throw new RuntimeException(String.format("Line number '%s, nextValue '%s''", lineNumber, nextValue), ex);
    }


}

Sample text (csv) file:

"ZIPCODE","CITY","STATE","LATITUDE","LONGITUDE","POPULATION"
"06778","NORTHFIELD","CT",41.707,-73.105,555
"06779","OAKVILLE","CT",41.595,-73.081,777
"06782","PLYMOUTH","CT",41.657,-73.041,888
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!