我正试图使用带有分隔符"\s\s"的Scanner将多个数据类型的文件读取到ArrayList对象中,但它似乎无法按预期工作。我正在使用printf查看数据是否正确存储,我稍后将使用这些数据进行计算。数据似乎显示正确,但我仍然收到"文件格式不正确"的异常。循环似乎也有问题。在使用对象的ArrayList时,我总是会陷入困境。
示例文本文件:
item item descr 100 1.50
item2 item descr 250 2.50
item2 item descr 250 3.50
代码:
import java.io.*;
import java.util.*;
public class ReadItems
{
private Scanner input;
ArrayList<Item> item = new ArrayList<Item>();
//open text file
public void openFile()
{
try
{
FileReader in = new FileReader("Items.txt");
input = new Scanner(in).useDelimiter("\s\s");
}
catch( FileNotFoundException fileNotFound)
{
System.err.println( "Error opening file.");
System.exit(1);
}
}
//read file
public void readFile()
{
try
{
while ( input.hasNextLine())
{
item.add( new Item(input.next(), input.next(), input.nextInt(), input.nextFloat() ));
for (Item list : item)
{
System.out.printf("%-10s%-48s$%5.2fn", list.getCode(), (list.getDecription()+ ", "+ list.getWeight()+ "g"), + list.getPrice());
//System.out.println(item);
}
}
}
catch ( NoSuchElementException elementEx)
{
System.err.println( "Incorrect file format.");
System.exit(1);
}
catch ( IllegalStateException stateEx )
{
System.err.println( "Error reading from file.");
System.exit(1);
}
}
public void closeFile()
{
if (input != null)
input.close();
}
}
输出:
item item descr, 100g $ 1.50
item item descr, 100g $ 1.50
item2 item descr, 250g $ 2.50
item item descr, 100g $ 1.50
item2 item descr, 250g $ 2.50
item2 item descr, 250g $ 3.50
文件格式不正确
对不起,我好像在做一件蠢事。我没有在main
所在的测试类中运行该程序。
测试等级:
public class TestReadItems
{
public static void main(String[] args)
{
ReadItems application = new ReadItems();
application.openFile();
application.readFile();
application.closeFile();
}
}
程序运行时没有错误,但是我似乎无法使while循环正常工作。产量增加了两倍。
这是因为打印输出的for
循环位于while
循环内。因此,它读取文件的每一行并返回输出。因此,要进行更正,请替换while
语句中的输出for
循环,并在while
循环完成后将其写入。
循环也可能在文件末尾出现垃圾。我在item.add()调用之后添加了对.nextLine()的调用,现在它对我来说很好。
while ( input.hasNextLine()) {
item.add( new Item(input.next(), input.next(), input.nextInt(), input.nextFloat() ));
for (Item list : item) {
System.out.printf("%-10s%-48s$%5.2fn", list.getCode(), (list.getDecription()+ ", "+ list.getWeight()+ "g"), + list.getPrice());
}
input.nextLine(); // added
}