易截截图软件、单文件、免安装、纯绿色、仅160KB

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中FileHelper的一个用法

 public boolean writeXML(String content, String filename)
    {  
        String savepath;
        FileOutputStream fout;
//        log.info("content:"+content+ ......

【转】Java synchronized用法搜集

在Java中,synchronized关键字为防止资源冲突提供了支持,其作用域有二种:
实例范围。
对象实例范围内synchronized使用的两种形式:
实例范围同步方法
publicd class syncTest {

synchronized void aMethod() {
//需要同步使用的代码
}

synchronized aMethod(){}可以防止多个线程同时 ......

Java设计模式系列教程(一)工厂模式factory

今天和大家一起学习Java的设计模式。本人的水平不是很高,这系列文章只是自己学习的过程,并希望能同大家分享经验。
先说下我对工厂模式的理解:当我们需要某个对象时,最直接的办法是看到这个对象就拿过来。但是当对象非常多的时候,找起来就很不方便。这时就需要一个中介来帮助我们取得想要的东西,这个中介就是工厂(fa ......

java文件过滤器的使用

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())) {
   ......

Java iText 动态 生成 PDF 文档 表格 中文问题

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 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号