我正在尝试将文本文件中的数据作为数组读取并拆分为类对象。我有一个ProductRecords类:
class ProductRecord
{
public String productCode;
public String category;
public String description;
public int aisleNumber;
public int currInventory;
public ProductRecord(String code, String category, String description, int number, int currInventory)
{
this.productCode = code;
this.category = category;
this. description = description;
this.aisleNumber = number;
this.currInventory = currInventory;
}
public String getProductCode() {
return productCode;
}
public String getCategory() {
return category;
}
public String getDescription() {
return description;
}
public int getAisleNumber() {
return aisleNumber;
}
public int getCurrInventory() {
return currInventory;
}
}
我试图从这个文件中读取
Thornton Hardware Store
7
P24-Qaa-1354 "hammer" "Bailey one-piece steel ripping hammer" 6 2
P24-Qbw-2495 "hammer drill" "Holsinger hammer drill, 8.5A 1/2-in" 7 1
P33-Qes-4782 "screwdriver" "Bailey 18-piece screwdriver set" 5 2
P25-Taa-1244 "nail" "Yolen framing nails, 50-count 3-1/4-in 28-degree" 6 20
P25-Tab-3509 "nail" "Yolen finish nails, 1000-count 18-guage 2-in" 6 9
P25-Tab-3506 "nail" "Yolen finish nails, 1000-count 16-guage 2-1/2-in" 6 14
P25-Tac-3672 "nail" "Yolen roofing nails, coil 1-1/4-in" 8 5
LC "nail"
LC "plant"
LP P24-Qbw-2495
LP P62-Aaa-1387
S P25-Tab-3506 5
S P24-Qbw-2495 1
R P25-Tab-3509 10
第一个信息是商店的名称,第二个信息是库存中的商品总数。所以例如在第三行存储在类
中P33-Qes-4782 "screwdriver" "Bailey 18-piece screwdriver set" 5 2
P33-Qes-4782 --> productCode
"screwdriver" --> category
"Bailey 18-piece screwdriver set" --> description
5 --> aisle number
2 --> current inventory
当我尝试拆分它时,它会拆分类别和描述之间的空白,我不希望这样。这是我的代码。
有没有办法在不影响扫描仪支架中的空白区域的情况下拆分它?
Scanner input = new Scanner(System.in);
System.out.println("Enter the input fileName: ");
String fileName = input.nextLine();
try {
Scanner file = new Scanner(new File(fileName));
System.out.println();
//number of products in the inventory
String inLine = file.nextLine(); // stores the name of the store
String line = file.nextLine();
int numberOfItems = Integer.parseInt(line);
System.out.println(numberOfItems);
System.out.println("*************************");
while (file.hasNextLine()) {
String[] tokens = file.nextLine().split(" ");
//String[] tokens = file.nextLine().
for (int i = 0; i < 5; i++) {
System.out.println(tokens[i]);
//System.out.println("\n");
}
System.out.println("\n");
}
/*ProductRecord[] records = new ProductRecord[file.nextInt()];
records[0].productCode = file.next();
System.out.println(records[0]);*/
/* for(int i =0; i < numberOfItems;i++)
{
//records[i] = new ProductRecord([])
}*/
} catch (IOException ioe) {
System.out.println("file not found");
}
答案 0 :(得分:0)
使用String[] tokens = file.nextLine().split("\"")
代替String[] tokens = file.nextLine().split(" ")
,它将成功删除" "
,并维护所附字符串的结构。
但是,需要对您的逻辑进行更改以解决此更改,因为调试语句会使用此方法丢失其当前格式。