2011-03-24 20 views
0

我在Java很新,我会缺少一些非常基本的东西。当我运行我的代码时,我正在尝试为代码中创建的帐户添加值。当我尝试运行代码时,我收到一个文件无法找到的错误,但我认为该文件是在代码中创建的。我的Java代码是有缺陷的,但我不明白为什么

import java.util.Scanner; 
import java.io.File; 
import java.io.IOException; 

class DoPayroll 
{ 
public static void main(String args[]) 
            throws 
     IOException  
{ 
    Scanner diskScanner = 
     new Scanner(new File("EmployeeInfo.txt")); 

    for (int empNum = 1; empNum <= 3; empNum++) 
    { 
     payOneEmployee(diskScanner); 
    } 
} 

static void payOneEmployee(Scanner aScanner) 
{ 
    Employee anEmployee = new Employee(); 

    anEmployee.setName(aScanner.nextLine()); 
    anEmployee.setJobTitle(aScanner.nextLine()); 
    anEmployee.cutCheck(aScanner.nextDouble()); 
    aScanner.nextLine(); 
} 
} 

运行一次我收到以下错误

Exception in thread "main" java.io.FileNotFoundException: EmployeeInfo.txt (No such file or directory) 
at java.io.FileInputStream.open(Native Method) 
at java.io.FileInputStream.<init>(FileInputStream.java:106) 
at java.util.Scanner.<init>(Scanner.java:636) 
at DoPayroll.main(jobexe.java:11) 

我认为在使用new Scanner(new File("EmployeeInfo.txt")上面的代码将创建一次,我输入一个值的新文件。请给我一个简单的解决方案和解释。

回答

0

您错误地实例化类文件实例与实际写入临时文件到磁盘。走这条线

Scanner diskScanner = 
     new Scanner(new File("EmployeeInfo.txt")); 

而与此

File newFile = File.createTempFile("EmployeeInfo", ".txt"); 
Scanner diskScanner = new Scanner(newFile); 

编辑替换:彼得使得一个好点。我现在正在面对现实。

+1

-1:创建一个空的临时文件并读取它有什么意义?你知道它里面没有任何东西。 – 2011-03-24 15:43:11

0

你认为是错误的:D Scanner需要一个现有的文件,这看起来很合逻辑,因为它读取值,而没有现有的文件难以阅读。该documentation还指出:

抛出: FileNotFoundException异常 - 如果源文件未找到

因此,简而言之:你必须提供一个可读的,现有的文件扫描仪。

1

File对象无法找到您传递的文件名。您需要将EmployeeInfo.txt的完整路径传递给new File(...)或确保当前工作目录是包含此文件的目录。

1

构造函数File不创建文件。相反,它创建访问磁盘上文件所需的Java信息。您必须使用创建的File来实际执行Java文件IO才能创建新文件。

Scanner constructor需要现有的File。所以你需要一个完整的路径到EmployeeInfo.txt的真实有效位置,或者首先使用File I/O创建该文件。在Java中的I/O上的This tutorial将有所帮助。

2

它将在您写入时创建一个新文件。但是要从中读取,它必须已经存在。您可能希望检查它是否存在与

File file = new File("EmployeeInfo.txt"); 
if (file.exists()) { 
    Scanner diskScanner = new Scanner(file); 
    for (int empNum = 1; empNum <= 3; empNum++) 
     payOneEmployee(diskScanner); 
} 
0

正如其他答案所解释的,该文件不是仅使用new File("EmployeeInfo.txt")创建的。 可以使用

file.createNewFile(); 

该方法返回true检查的文件是否存在使用

File file = new File("EmployeeInfo.txt"); 
if(file.exists()) { 
    //it exists 
} 

,或者你可以创建文件(如果不存在,但它),如果该文件被创建和false如果它已经存在。

相关问题