Java新手。
我有一个txt文件:
在一个名为Goods的类中,我已经能够读取它,使用分隔符将其拆分,将其添加到ArrayList。
我有另一个名为GoodsList的类,我将在其中创建一个ArrayList,它应该具有上面的对象,如果用户请求它我可以使用它。感谢
答案 0 :(得分:1)
我认为你在询问java泛型。 如果是这样,请创建Goods类,因为您需要通过ArrayList将其作为对象访问。
public Class Goods implements Serializable {
private String goodName;
private double price;
private int quantity;
public String getGoodName() {
return goodName;
}
public void setGoodName(String goodName) {
this.goodName = goodName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
然后编写GoodsList类以创建包含您设置的Goods对象的列表:
public class GoodsList {
public static void main(String args[]) {
Goods g = new Goods();
Goods g2 = new Goods();
Goods g3 = new Goods();
g.setGoodName("hat");
g.setQuantity(50);
g.setPrice(100.00);
g2.setGoodName("pants");
g2.setQuantity(50);
g2.setPrice(100.00);
g3.setGoodName("shoes");
g3.setQuantity(50);
g3.setPrice(100.00);
List < Goods > goodsList = new ArrayList < Goods > ();
goodsList.add(g);
goodsList.add(g2);
goodsList.add(g3);
//printing goods:
for (Goods g: goodsList) {
System.out.println(g.getGoodName() + "," + g.getQuantity() + "," + g.getPrice());
}
}
}
是你要找的东西吗?
答案 1 :(得分:0)
您正在寻找类似的东西:
public class FileReaderExample
{
public class Goods
{
private String goodName = null;
private String price = null;
private String quantity = null;
public Goods(String goodName ,String price,String quantity)
{
this.goodName = goodName;
this.price = price;
this.quantity = quantity;
}
public String getGoodName()
{
return goodName;
}
public void setGoodName(String goodName)
{
this.goodName = goodName;
}
public String getPrice()
{
return price;
}
public void setPrice(String price)
{
this.price = price;
}
public String getQuantity()
{
return quantity;
}
public void setQuantity(String quantity)
{
this.quantity = quantity;
}
}
private ArrayList<Goods> populateGoods()
{
ArrayList<Goods> goodsList = new ArrayList<Goods>();
File file = new File("d:\\text.txt");
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null)
{
String[] itemsOnLine = line.trim().split(",");
goodsList.add(new Goods(itemsOnLine[0],itemsOnLine[1],itemsOnLine[2]));
}
}
catch (IOException e)
{
e.printStackTrace();
}
return goodsList;
}
public static void main(String[] args)
{
FileReaderExample fileReaderExample = new FileReaderExample();
ArrayList<Goods> goodsList = fileReaderExample.populateGoods();
for (Goods goods : goodsList)
{
System.out.println(goods.getGoodName());
}
}
}