while( inStream.hasNextLine() )
{
...
lineList.add( inStream.nextLine() );
}
...
lineList 是一个 ArrayList。该代码很好地阅读了所有内容,但它不会抓住最后一行。文本文件中的最后两行如下所示:
"a sentence here..."
<a blank line here. the blank line is the last line>
我假设它不会抓住它,因为 hasNextLine() 没有检测到这一行之后的另一行?
有什么方法可以抓住最后一行?我认为阅读直到它是 EOF 然后捕获异常可能会起作用,但似乎没有办法做到这一点。
编辑:更多信息
public void readLines()
{
lineList = new ArrayList();
try
{
inStream = new Scanner( new File( fileName ) );
}
catch( FileNotFoundException e )
{
System.out.println( "Error opening the file. Try again." );
}
if ( inStream != null )
{
while( inStream.hasNextLine() )
{
++originalLines;
lineList.add( inStream.nextLine() );
}
inStream.close();
}
}
方法全了。哪里不对了?
编辑:更多信息
public static void main(String[] args)
{
Scanner inStream = null;
String test = "";
inStream = new Scanner( test );
while( inStream.hasNextLine() )
{
System.out.println( inStream.nextLine() );
}
}
它不会拾取空字符串,但会拾取空格“”