java - 缓冲读取器 "Unknown Source"

标签 java arraylist bufferedreader

我正在尝试读取一个包含产品描述、产品代码和产品价格的文件。我拥有它,以便它将在每个新行中设置 Product 的变量,直到它等于 null:

public class ReadFile {

static ArrayList<Product> products = new ArrayList<Product>();

public static void main(String[] args){

    String line;

    try {
        BufferedReader bufferedReader = new BufferedReader (new FileReader("C:/Users/Tom/Desktop/data.txt"));

        while ((line = bufferedReader.readLine()) != null){
            Product product = new Product();
            product.setDescription(bufferedReader.readLine());
            product.setProductCode(bufferedReader.readLine());
            product.setUnitPrice(Integer.parseInt(bufferedReader.readLine()));
            System.out.println(product);
            products.add(product);
            }
    bufferedReader.close();
    }   
    catch(IOException e){
        System.out.println("File not found.");

}}

但是,当涉及到获取文件中的下一个产品(Pear)时,我收到错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Pear"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at controller.ReadFile.main(ReadFile.java:24)

文件的设置方式如下:

Apple /r 01 /r 99 /r Pear /r 02 /r 88

注意:/r 用于表示文件中的新行。

我哪里出错了,它会创建一个新产品,设置信息并重复直到该行等于空?

最佳答案

您正在阅读产品类型的两遍。只需使用line变量的值来设置产品描述。

while ((line = bufferedReader.readLine()) != null){
  // line has already stored information about the Product type.
            Product product = new Product();
            product.setDescription(line); // set value using line variable
            // product.setDescription(bufferedReader.readLine()); // error
            product.setProductCode(bufferedReader.readLine());
            product.setUnitPrice(Integer.parseInt(bufferedReader.readLine()));
            System.out.println(product);
            products.add(product);
            }

关于java - 缓冲读取器 "Unknown Source",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49212041/

相关文章:

java - 响应错误时无法关闭 http 流

Java/Eclipse - 在主方法之外使用 BufferedReader 时解决 IOException

Java-TestNG : Read an excel file, 通过 TestNG 和 Apache POI 断言并写回 excel 文件

java - 编写递归预序树搜索,以列表形式返回答案

Java 邮件客户端到 MS Exchange 服务器

java - 组合两个 if 语句

java - 如何看待 Java 线程?又名 Thread.stop

JavaFX:使用对象属性的组合框

java - 在创建 ArrayList 时添加元素

java - BufferedReader readLine 返回 null