Java 如何在读取最后一个值时再次从文本文件中读取整数

Java 如何在读取最后一个值时再次从文本文件中读取整数,java,file,Java,File,有这样一个文本文件: >3 >7 >9 >5 我使用nexInt()读取所有值。现在我想再次读取第一个值。但在这种情况下调用nextInt方法时,我只得到以下结果: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at jav

有这样一个文本文件:

>3
>7
>9
>5
我使用nexInt()读取所有值。现在我想再次读取第一个值。但在这种情况下调用nextInt方法时,我只得到以下结果:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at files.main(files.java:49)

如何将光标再次转到第一行

您可以从列表中读取您的号码

Scanner scanner = new Scanner(new File("file.txt"));
List<Integer> numbers = new ArrayList<Integer>();

while(scanner.hasNextInt())
{
     numbers.add(scanner.nextInt());
}

使用Scanner是不可能的,但是,您始终可以重新声明Scanner(仅当您要再次执行此重复操作时)

如果要多次扫描列表,并希望来回浏览,则可能应该使用RandomAccessFile

RandomAccessFile raf = new RandomAccessFile(myFile), "r");
// do something

// later reset to the begining
raf.seek(0);

或者将数字保存在列表中,稍后再对其进行迭代

有多种方法可以做到这一点

您可以使用:
if(Scanner.hasNextInt()){}
以避免出现异常,然后使用
reset()
函数


或者像Yohan E所说的那样,将数字写入列表或数组列表,然后在列表上交互。

相关:将数字存储在合适的
集合中
,并在必要时重新迭代……您是否尝试过Scanner.reset()?
// re-declare
scan = new Scanner(myFile);
RandomAccessFile raf = new RandomAccessFile(myFile), "r");
// do something

// later reset to the begining
raf.seek(0);