使用scanner类读取.txt时出错

时间:2013-04-11 15:41:01

标签: java exception java.util.scanner

我正在研究一个程序来读取二进制文件并将其更新为一个txt文件,它突然工作了,它开始抛出这个错误

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at StockManage.updateInv(StockManage.java:134)
    at StockManage.main(StockManage.java:173)

继承导致错误的代码

try
{
    Scanner trans = new Scanner(new File(file));
    RandomAccessFile inv = new RandomAccessFile (file2,"rws");
    String tempName = "Temp" + (int)(Math.random()*1000000) + ".dat";
    RandomAccessFile newInv = new RandomAccessFile (tempName , "rws");
    File newFile = new File(tempName);

    String transISBN = trans.next();
    String author = inv.readUTF();
    String title = inv.readUTF();
    String iSBN = inv.readUTF();
    int amount = inv.readInt();

    while (inv.getFilePointer()<=inv.length())
    {
        boolean empty = true;

        while (empty&&trans.hasNext())
        {

            if (iSBN.compareTo(transISBN)<0)
            {
                empty = false;
                break;
            }
            else if (iSBN.compareTo(transISBN)==0)
            {
                int change = trans.nextInt();
                amount += change;
                transISBN = trans.next();
            }
        }

        newInv.writeUTF(author);
        newInv.writeUTF(title);
        newInv.writeUTF(iSBN);
        newInv.writeInt(amount);

        author = inv.readUTF();
        title = inv.readUTF();
        iSBN = inv.readUTF();
        amount = inv.readInt();


    }

我真的陷入了这个,所以任何帮助都会很棒

2 个答案:

答案 0 :(得分:2)

在Scanner对象上调用next()之前,你应该调用hasNext()来检查是否有更多的数据需要读取。

答案 1 :(得分:0)

此代码部分容易出错:

else if (iSBN.compareTo(transISBN)==0)
{
    int change = trans.nextInt();
    amount += change;
    transISBN = trans.next();
}

您可以在trans.hasNext()中控制while loop,但在transISBN = trans.next();之前没有if(trans.hasNext())在{{1}}之上,问题将会解决,我猜。