Java Scanner NoSuchElementException
今天同学问我一个Java问题,代码结构如下:
Scanner scan = new Scanner(System.in);
scan.next();
scan.close();
scan = new Scanner(System.in);
scan.next();
当程序运行到第五行是会抛出java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
于是按照错误栈的轨迹查找原因。
简要的说,就是前后两次实例化的参数System.in是用一个对象,是InputStreamReader对象,每个该对象包含一个
StreamDecoder 实例 sd
private final StreamDecoder sd;
而scan.close()方法为
public void close() {
if (closed)
return;
if (source instanceof Closeable) {
try {
((Closeable)source).close();
} catch (IOException ioe) {
lastException = ioe;
}
}
sourceClosed = true;
source = null;
closed = true;
}
当执行到 ((Closeable)source).close();就会进入InputStreamReader的close()方法:
public void close() throws IOException {
sd.close();
}
这里的sd就是上面提到的InputStreamReader对象,(有查了StreamDecoder 源代码,但没更深入下去),此时sd已关闭。
当执行如错误产生代码的第5行代码 scan.next()时,
public String next() {
ensureOpen();
clearCaches();
while (true) {
String token = getCompleteTokenInBuffer(null);
if (token != null) {
matchValid <mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js"></mce:script><mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/lan
相关文档:
java文件过滤器的使用代码如下:
测试代码:package file;
import java.io.File;
public class fileFilter {
public static void main(String[] args) {
File file = new File("d:\\");//设置文件路径
for (File fileList : file.listFiles(new file.MyFileFilter())) {
......
package test;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class XmlTest {
public static void main(String[] args) {
File xmlFile=new File("test/xml.xml");
DocumentBuilderFactory documentBuilderFactor ......
今天观看了蓝山老师java背后的秘密相关视频,发现要想写出高性能的程序,一定要对其运行原理以及其运行环境有相当程度的了解。那ClassLoader是相当关键的一个部分。
先说下java程序运行的基本流程,先将java文件编译为class文件,然后通过ClassLoader(类加载器),加载到Runtime Data Area(类似于内存)中 ......
import java.awt.Color;
import java.io.FileOutputStream;
import com.lowagie.text.Cell;
import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.List;
import com.lowagie.text.ListItem;
import com.lo ......