Scanner类中有不少可以查看文件是否结束的方法,比如下面的代码使用的是hasNextLine方法
package com.li;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.util.*;public class Main { public static void main(String[] args) { // TODO 自动生成的方法存根 Scanner inputStream = null; try { inputStream = new Scanner(new FileInputStream("stuff.txt")); }catch(FileNotFoundException e) { System.out.PRintln("File stuff.txt was no found"); System.exit(0); } String line = null; while(inputStream.hasNextLine()) { line = inputStream.nextLine(); System.out.println(line); } inputStream.close(); }}使用hasNextLine方法在读到结尾的时候会返回一个false值,从而可以判读文件读完了(注意有一个NextLine方法在读到/n会自动将其抛弃),针对不同的数据类型,Scanner还为我们提供了hasNextInt,jasNextLong,hasNextShort……等等一些方法,它们的使用方法都是大同小异的。
使用BufferedReader类中的read和readLine方法来判断即可,对于read方法,当返回-1的时候就可以知道读完了,对于readLine方法,当返回false的时候就知道读完了。
新闻热点
疑难解答