我有一个包含以下内容的数据文件“ inventory.dat”:
Item ID |Item Name |Item Description |Weight |Quantity |Price |Isle |Bin
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
BK1012923 |#8 x 1" Wood Screws (Qty 8) |#8 x 1" Wood Screws (Qty 8) - Plastic bag |0.04 |144 |0.65 |Isle-N23 |Bin-N23-14-3
BK1022344 |#8 x 1" Wood Screws (Qty 8) |#8 x 1 1/2" Wood Screws (Qty 8) - Plastic bag |0.06 |144 |0.65 |Isle-N23 |Bin-N23-14-3
BK1022344 |#8 x 1" Wood Screws (Qty 8) |#8 x 1 1/2" Wood Screws (Qty 8) - Plastic bag |0.06 |50 |0.65 |Isle-S18 |Bin-S18-01-2
Summary: 338 items Total Value: $219.70
我希望能够将每条数据读入单独的变量中,分别用于项目ID,项目名称,项目说明,重量,数量,价格,岛和箱。我将如何使用BufferedReader
来做到这一点?
摘要和总值应忽略。
import java.io.*;
import java.util.*;
/**
*
*
*/
public class FileRead {
public static void main (String[] argv) {
BufferedReader reader;
String line;
String data;
ArrayList<String> itemID = new ArrayList<String>();
ArrayList<String> itemName = new ArrayList<String>();
ArrayList<String> itemDesc = new ArrayList<String>();
ArrayList<String> weight = new ArrayList<String>();
ArrayList<Integer> quant = new ArrayList<Integer>();
ArrayList<Float> price = new ArrayList<Float>();
ArrayList<String> aisle = new ArrayList<String>();
ArrayList<String> bin = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader("resources/inventory.dat"));
while ((line = reader.readLine() != null)) {
//
}
}
catch (IOException e)
{
System.err.println(e);
}
}
}
答案 0 :(得分:0)
这是一种实现方法。我使用line.split("\\|")
来分隔行,并以|
作为分隔符。而且由于摘要和总计之前文件中有一个空行,因此您可以使用if(line.isEmpty())
try {
reader = new BufferedReader(new FileReader("resources/inventory.dat"));
//ignore first two lines
line = reader.readLine(); //read first line
line = reader.readLine(); //read second line
line = reader.readLine(); //read third line
while (line != null){
if(line.isEmpty())
break;
String [] l = line.split("\\|"); //Split the lines
//Add data
itemID.add(l[0]);
itemName.add(l[1]);
itemDesc.add(l[2]);
weight.add(l[3]);
quant.add(Integer.parseInt(l[4].trim()));
price.add(Float.parseFloat(l[5].trim()));
aisle.add(l[6]);
bin.add(l[7]);
line = reader.readLine();
}
}