使用多个扫描仪时找不到文件

时间:2015-06-03 00:26:39

标签: java file input java.util.scanner

我在Eclipse中编写一个简单的程序来输入和比较两个文本文件。但是,我似乎无法同时导入这两个文本文件。如果我删除了一个新的扫描仪对象,它会清除我的其他文件;否则,它会给我一个错误,即两者都找不到该文件。这两个文件都在我的源文件夹中的相同位置。代码如下:

textfile1 = new File("Text1.txt");
Scanner text1 = new Scanner(textfile1);
textfile2 = new File("Text2.txt");
Scanner text2 = new Scanner(textfile2);

提前致谢!

1 个答案:

答案 0 :(得分:1)

使用try-catch块尝试此代码,并告诉我它是否有效。



// sometimes the compiler complains if there was a scanner opened without a try-catch block around it
try {
            final File FILE1 = new File("text1.txt"); //it is always a good thing to make a file as final, it gives an easy reference for the reader 
            final File FILE2 = new File("text2.txt");
            Scanner t1 = new Scanner(FILE1);
            Scanner t2 = new Scanner(FILE2);
            //after you are done close the scanner
            t1.close();
            t2.close();
        } catch (FileNotFoundException ex) {
        }