[英]How do I read and write a file from ArrayLists in Java
所以我有一個數組的以下讀寫文件程序。 對於ArrayList,以下內容如何? 我的語法有問題。 我知道一個ArrayList就是這樣的:private ArrayList prod list = new ArrayList(); BUt如何讀/寫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);
最后,用p
代替prodlist[pIndex]
所有用法,然后在其他地方刪除pIndex
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.