因此,此代码正在读取.txt文件,然后将值存储在arraylist中。我试图通过一个名为Product的简单构造函数输出结果。但是,当我尝试在page2.jsp中执行JSP for循环时,不会显示任何内容。当我尝试显示arrayList产品时,它也给了我一个nullpointerexception,但我没有看到读取该文件的类有任何问题。任何建议和帮助表示赞赏。
page2.jsp
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Iterator"%>
<%@page import="constructor.Product"%>
<%@page import="java.util.List"%>
<%@page import="data.ProductIO"%>
<body>
<%
ProductIO pro = new ProductIO();
ArrayList<Product> userList = pro.selectProducts();
//Iterator<Product> itr = userList.iterator();
//Product user = new Product();
%>
<table style="width:100%">
<%
for(Product product : userList) {
%>
<tr>
<td><%=product.getCode()%></td>
<td><%=product.getDescription()%></td>
<td><%=product.getPrice()%></td>
</tr>
<%
}
%>
</table>
</body>
ProductIO.java
public class ProductIO {
private static ArrayList<Product> products = null;
private static String filePath = "product.txt";
public static void main(String [] args) {
//System.out.println(products);
}
public static void init(String filePath) {
ProductIO.filePath = filePath;
}
public static ArrayList<Product> selectProducts() {
products = new ArrayList();
File file = new File("product.txt");
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
StringTokenizer t = new StringTokenizer(line, "|");
if (t.countTokens() >= 3) {
String code = t.nextToken();
String description = t.nextToken();
String priceAsString = t.nextToken();
double price = Double.parseDouble(priceAsString);
Product p = new Product();
p.setCode(code);
p.setDescription(description);
p.setPrice(price);
products.add(p);
}
line = in.readLine();
}
in.close();
return products;
} catch (IOException e) {
System.out.println(e);
return products;
}
}