如果我有多个属性,如何读取txt文件?

时间:2019-05-15 12:06:46

标签: java

我正在尝试获取一个类来读取我的txt文件,例如几行:

面部乳液,1、2、0.1

保湿乳液,2、3、0.2

化妆水3、4、0.3

芦荟乳液4、5、0.4

我创建了一个具有属性名称(字符串),productNo(int),productRating(int)和productDiscount(double)的类调用Lotion,并创建了另一个类ListOfLotion并添加了Lotion的数组列表。

我的问题是如何获取ListOfLotion类以使用txt文件中的值并将其放入我的arraylist中。

我尝试使用indexOf作为名称,直到下一个,但出现错误, java.lang.StringIndexOutOfBoundsException:开头为0,结尾为-1,长度为17

无论如何,我还是可以将所有四个值分开,并确保它们正确存储,例如,Facial Lotion作为名称存储,而1作为prodcuctNo存储。

public void addListOfLotion(){

    ArrayList<Lotion> lotion = new ArrayList<Lotion>();

    Scanner scanner = new Scanner("Desktop/Lotion.txt");

    while(scanner.hasNext()){

     String readLine = scanner.nextLine();

     int indexProductNo = readLine.indexOf(',');

     int indexOfProductRating = readLine.indexOf(',');

     double indexOfProductDiscount = readLine.indexOf(',');

      lotion.add(new Lotion(readLine.substring(0, indexOfProductNo),0,0,0));

    }scanner.close();

    }

Got this error as result: 
  java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 17
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
    at java.base/java.lang.String.substring(String.java:1874)
    at ListOfVenues.addListOfLotion(ListOfLotion.java:42)

是因为我将readLine,indexOf(',')用作每个readLine,它只是在第一个','处停止了吗?无论如何,我可以有效地让java知道此索引与该索引之间是名称,而此索引与该索引之间是productNo?

谢谢大家。

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式(Demo):

([\w\s]+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+(?:\.\d+))

您可以在类中定义为常量:

private static final Pattern LOTION_ENTRY = 
    Pattern.compile("([\\w\\s]+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+(?:\\.\\d+))");

然后,您可以为每个条目创建一个Matcher并提取组:

Matcher matcher = LOTION_ENTRY.matcher(readLine);

if(matcher.matches()) {
    String name = matcher.group(1);
    int no = Integer.parseInt(matcher.group(2));
    int rating = Integer.parseInt(matcher.group(3));
    double discount = Double.parseDouble(matcher.group(4));

    // do something
} else {
    // line doesn't match pattern, throw error or log
}

不过请注意:如果输入无效,parseInt()parseDouble可以抛出NumberFormatException。因此,您必须抓住这些并采取相应措施。

答案 1 :(得分:1)

由于行是逗号分隔的列表,因此您可以使用split()将行拆分为单个变量。
要考虑的另一件事是,Scanner("file.txt")不会读取指示的文本文件,而只会读取给定的String。您必须先创建一个File对象。

File input = new File("Desktop/Lotion.txt");
Scanner scanner;
scanner = new Scanner(input);
while(scanner.hasNext()){
    String readLine = scanner.nextLine();
    String[] strArray = readLine.split(",");
    int indexOfProductNo = Integer.parseInt(strArray[1].trim());
    int indexOfProductRating = Integer.parseInt(strArray[2].trim());
    double indexOfProductDiscount = Double.parseDouble(strArray[3].trim());
    lotion.add(new Lotion(strArray[0],indexOfProductNo,indexOfProductRating,indexOfProductDiscount));
}