2012-12-04 45 views
1

我正在尝试读取名为“KFormLList.txt”的Java文件。它与该程序一起保存在默认包中,但是当我尝试运行它时,出现以下错误消息:“错误:KFormLList.txt(系统找不到指定的文件)”FileInputStream错误Java

我在做什么错误?谢谢你的帮助。

import java.io.*; 

public class VLOCGenerater { 

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    try { 
     //Read the text file "KFormLList.txt" 
     FileInputStream fis = new FileInputStream("KFormLList.txt"); 

     DataInputStream dis = new DataInputStream(fis); 
     BufferedReader br = new BufferedReader(new InputStreamReader(dis)); 
     String strLine; 
     int V = 0; 
     int LOC = 0; 

     while((strLine = br.readLine())!= null){ 
      if (strLine.trim().length() != 0){ 
       System.out.println(strLine); 
       V++; 
       } 
      else { 
       LOC++; 
      } 
     } 
     System.out.println("V = " + V); 
     System.out.println("LOC = " + LOC); 
     dis.close(); 
    } 
    catch (Exception e){ 
    System.err.println("Error: " + e.getMessage()); 
    } 

} 

} 
+0

文本文件与执行程序的位置相同吗? –

+0

是的。文本文件(KFormLList.txt)与程序(VLOCGenerater.java)位于同一个文件夹(src)中。 – Brett

回答

5

尝试将文本文件放在项目的根目录中。

传递给FileInputStream构造函数的name参数是文件系统中文件的路径名。

A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

我以为你是使用Eclipse,通过Eclipse默认设置user.dir到项目的根目录下。从阅读其他材料,Netbeans遵循相同的惯例。

这可以用下面的代码进行测试,这应该输出路径到您的项目:

System.out.println(System.getProperty("user.dir")); 

将文件放到你的根目录下允许其被FileInputStream找到。

0

这样,程序需要工作文件夹中的文件。即执行java的地方。对于从类路径(默认包)加载,请尝试getResourceAsStream。

1

如果你使用的是NetBeans(也许是类似的Eclipse),请确保您的文件在的NetBeansProjects/YourProject/

如果你编译你的程序.jar文件,把TXT,以相同的地方.jar是。

1

可以将文件放在项目的“根目录”中,或者将文件的“绝对路径”作为FileInputStream的参数提供。

希望有所帮助。 :)。

相关问题