Java 从文本文件读取数据并创建对象

Java 从文本文件读取数据并创建对象,java,bufferedreader,readfile,stringtokenizer,writefile,Java,Bufferedreader,Readfile,Stringtokenizer,Writefile,我需要一些帮助: 我正在用Java做一个超市模拟,但我有一个问题,我有一个文本文件(Stock.txt),里面有所有超市的库存,例如: 0-面包店-巧克力蛋糕-12.5-250美元 1块肉-优质牛排-2.6-120美元 2-海鲜-金枪鱼-1.2-14美元 其中第一个数字是产品的“id”,第二个是产品所属的部门,第三个是产品名称,第二个是价格,最后一个数字是库存产品的数量。 我有这门课: public class Product { protected String name;

我需要一些帮助: 我正在用Java做一个超市模拟,但我有一个问题,我有一个文本文件(Stock.txt),里面有所有超市的库存,例如:

  • 0-面包店-巧克力蛋糕-12.5-250美元
  • 1块肉-优质牛排-2.6-120美元
  • 2-海鲜-金枪鱼-1.2-14美元
其中第一个数字是产品的“id”,第二个是产品所属的部门,第三个是产品名称,第二个是价格,最后一个数字是库存产品的数量。 我有这门课:

public class Product {
    protected String name;
    protected double price;
    protected String department;
    protected int id;
    protected int stock;
}
因此,基本上我需要做的是从文本文件中读取每一行并创建产品,即对于第一行,制作如下内容:

Product product1 = new Product(0,"Bakery","Chocolate Cake", 12.5, 250);     
然后将其添加到数组中

Product[0] = product1;
对于文本文件中的所有内容,当运行模拟时,每个客户都会随机购买随机数量的随机库存产品,因此库存数量将减少。最后,当模拟结束时,程序必须在同一文本文件中写入每个产品的修改量

问题是,也许这太容易了,但我不知道如何做到这一点,因为从我开始用Java编程(我是一个初学者)起,用Java读写文件对我来说是一个真正的问题。 我有一些关于使用BufferedReader和StringTokenizer类来读取和创建对象问题的想法,但我不知道该怎么做,也不知道该怎么做覆盖问题。 我真的很感激你的帮助


哦!!顺便说一句,我真的只需要使用数组,所以使用ArrayList或任何其他结构都不是一种选择:(

为了简单起见,我将所有项定义为字符串

产品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
将产品列表放在“testData/product.txt”中。这是假设产品列表的格式相同,即id部门名称价格库存\n

使用下面的jUnit测试来测试您的代码。您当然可以修改如何读取product.txt文件(可能是其他功能强大的字符串读取器)

@测试
公开无效测试(){
试一试{
List productLines=Files.readAllLines(java.nio.file.path.get(“./testData/product.txt”)、StandardCharsets.UTF_8);
for(字符串行:productLines)
产品=新产品();
String[]tokens=line.split(“-”);
product.setId(令牌[0]);
product.setDepartment(代币[1]);
product.setName(令牌[2]);
产品定价(代币[3]);
产品设置库存(代币[4]);
System.out.println(product.toString())
}
}捕获(IOE异常){
e、 printStackTrace();
}
} 

这对于
扫描仪读入数据来说是一项很好的工作。如果不能使用像
ArrayList
这样的集合,您必须自己动态重新分配阵列

请尝试以下操作:

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);
    }
}
结果:

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
给未来的读者

我的csv(逗号分隔值)文件周围有双引号。 还有一些双打和整数

我还疯狂地试图在csv文件中找到一条“错误的行”和正在呕吐的值。因此,我的异常显示了一条正确的消息

我的“分隔符”是逗号和回车符,我处理双引号“在列级别”

这是我想到的

 /* 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);
    }


}
 /* 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);
    }


}
"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