如何在java中以特定方式从文件中打印字符串?

时间:2016-05-25 14:24:29

标签: java file java.util.scanner

我的文件名为“examples.txt”,数据为 a1 b4
a7 b6
a3 b9
我想分别从每一行打印每个字符串 a1 b4 Ι写了这段代码

try  
{   
    FileInputStream inputStream = new FileInputStream("example.txt");  
}  
catch (FileNotFoundException e)  
{    
    System.out.println("Problem opening file.");   
    System.exit(0);    
}  
Scanner inputReader = new Scanner(inputStream);  
while (inputReader.hasNextLine())  
{                           
    System.out.println(inputReader.next());  
    System.out.println(inputReader.next());  
}   

这段代码正是我想要的,打印所有数据直到最后一行,但它导致运行时错误java.util.NoSuchElementException,我不明白为什么。有没有解决这个问题的方法?

1 个答案:

答案 0 :(得分:1)

您正在寻找的是:

// Iterate as long as you have remaining lines
while (inputReader.hasNextLine()) {
    String line = inputReader.nextLine();
    // For each line, slip the tokens using space as separator
    for (String token : line.split(" ")) {
        System.out.println(token);
    }
}

<强>输出:

a1
b4
a7
b6
a3
b9

响应更新:

实际上你的代码也有效,你面临的问题可能是由于文件末尾有一个空行,的确是因为它是一个真行,即使它是空的hasNextLine()将返回{{1但是,由于没有更多令牌,因此当您致电true时,它会抛出NoSuchElementException。使用我的方法,你没有这个问题,因为空行将返回一个空数组。