简体   繁体   English

如何从Java中的ArrayLists读取和写入文件

[英]How do I read and write a file from ArrayLists in Java

So I have the following read and write file program for an Array. 所以我有一个数组的以下读写文件程序。 How would the following look like for an ArrayList? 对于ArrayList,以下内容如何? I am having trouble with the syntax. 我的语法有问题。 I know an ArrayList would be like that: private ArrayList prod list = new ArrayList(); 我知道一个ArrayList就是这样的:private ArrayList prod list = new ArrayList(); BUt how would the read/write IO syntax be? BUt如何读/写IO语法? Thank you. 谢谢。

    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++;
        }
    }

Replace this: 替换这个:

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

with

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

then this: 这个:

        prodlist[pIndex] = new ActionProduct();

with

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

Finally, replace all uses of prodlist[pIndex] with p , then get rid of pIndex everywhere else. 最后,用p代替prodlist[pIndex]所有用法,然后在其他地方删除pIndex

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM