gpt4 book ai didi

java - 如何在 Java 中从 ArrayList 读取和写入文件

转载 作者:行者123 更新时间:2023-12-02 07:53:27 25 4
gpt4 key购买 nike

所以我有以下用于数组的读写文件程序。对于 ArrayList 来说,以下内容会是什么样子?我的语法有问题。我知道 ArrayList 会是这样的: private ArrayList prod list = new ArrayList();但是读/写 IO 语法是怎样的呢?谢谢。

    static ActionProduct[] prodlist = new ActionProduct[50];
static String filename = System.getProperty("user.dir") + "\\src\\product.txt";
static int pIndex=0;


public static void readFile() throws IOException {
// input file must be supplied in the first argument
InputStream istream;
if (filename.length() > 0) {
File inputFile = new File(filename);
istream = new FileInputStream(inputFile);
} else {
// if no filename, use standard input stream
istream = System.in;
}

// use a buffered reader for line-at-a-time
// reading
BufferedReader lineReader;
lineReader = new BufferedReader(new InputStreamReader(istream));

// read one line at a time
String line;
while ((line = lineReader.readLine()) != null) {

StringTokenizer tokens = new StringTokenizer(line, "\t");

// String tmp = tokens.nextToken();
// System.out.println("token " + tmp);
prodlist[pIndex] = new ActionProduct();
String category = prodlist[pIndex].getCategory();
category = tokens.nextToken();
System.out.println("got category " +category);

int item = prodlist[pIndex].getItem();
item = Integer.parseInt(tokens.nextToken());

String name = prodlist[pIndex].getName();
System.out.println("got name " +name);

double price = prodlist[pIndex].getPrice();
price = Double.parseDouble(tokens.nextToken());

int units = prodlist[pIndex].getUnits();
units = Integer.parseInt(tokens.nextToken());
pIndex++;
}
}

最佳答案

替换这个:

static ActionProduct[] prodlist = new ActionProduct[50];

static List<ActionProduct> prodlist = new ArrayList<ActionProduct>();

然后这个:

        prodlist[pIndex] = new ActionProduct();

        ActionProduct p = new ActionProduct();
prodlist.add(p);

最后,将 prodlist[pIndex] 的所有使用替换为 p,然后在其他地方删除 pIndex

关于java - 如何在 Java 中从 ArrayList 读取和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com