Netbeans FileReader FileNotFound文件在文件夹中时出现exception?

所以问题是我每次尝试在NetBeans或Eclips上加载下面的代码时都会抛出exception,但是当我尝试通过TextMate运行它时一切正常!

我试着把绝对地址,改成文本文件等..没有帮助!

有人可以帮助我或告诉它为什么不能用IDE运行?

谢谢

void loadFile() { try { list = new LinkedList(); FileReader read = new FileReader("a.txt"); Scanner scan = new Scanner(read); while (scan.hasNextLine()) { String Line = scan.nextLine(); String[] subArray = new String[5]; subArray = Line.split(","); int a = Integer.parseInt(subArray[4]); list.add(new Patient(Integer.parseInt(subArray[0]), subArray[1], subArray[2], subArray[3], a)); } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } cap = list.size(); search_names = new int[cap]; for (int i = 0; i < list.size(); i++) { search_names[i] = i; } setNames(search_names); }//end loadFile 

调试日志: Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsfd.jar Have no file for /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Resources/Java/JavaRuntimeSupport.jar Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/sunrsasign.jar }

在netbeans中,默认工作目录始终是根文件夹,我的意思是包含名称为“src”,“build”等文件夹的文件夹。将文件与这些文件夹一起放置,它就可以完成。

以下是NetBeans IDE 7.0.1中的分步过程

  1. 单击“文件”菜单。
  2. 单击“项目属性”。
  3. 在类别中,选择“运行”。
  4. 在主类中,您可以选择当前的java文件。
  5. 在Arguments中,选择要读取的文件,例如abc.txt或abc.java
  6. 在工作目录中记下此abc.txt或abc.java所在的文件夹的路径。
  7. 单击确定以关闭项目属性。
  8. 在运行程序时,不要忘记选择项目作为主项目。
  9. 然后在键盘上单击F ^。 即你必须运行你的主项目,而不是只运行你当前的java文件。 就是这样……享受!!!!

终于找到了解决方案

在eclipse中,您应该将目标文件放在项目文件夹中。 猜测同样适用于NetBeans。

我将目标文件放在“src”文件夹中(实际代码文件所在的位置)。 实际上我只需将其更改为项目文件夹所在的上层文件夹。

简单易用。

可能你在不同的设置中有不同的“工作目录” 。 您可以通过以下方式打印来检查您所在的目录:

 System.out.println(new File(".").getAbsoluteFile()); 

在eclipse中,您可以在运行配置,参数选项卡中设置工作目录。

试试BufferedReader?

编辑:编辑以更密切地显示您的代码示例。 使用文件阅读器时,我得到了优异。 但能够使用BufferedReader .println 。 我没有使用Scanner

编辑2:我也能让你的代码工作。 使用扫描仪等(使用完整路径时)(例如: FileReader read = new FileReader(""C:\\myfolder\\folder\\a.txt" 。所以嗯。

  try { list = new LinkedList(); BufferedReader scan = new BufferedReader(new FileReader("C:\\a.txt")); String lines; try { // Scanner scan = new Scanner(read); while ((lines = scan.readLine()) != null) { //I just printed lines you will do your stuff here System.out.println(lines); } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } 

右键单击文本文件选择属性并复制路径并将其粘贴到您输入文件名的位置

假设你想在netbeans中添加test.txt

如果您在C:\ myProject中的项目将文本文件直接放在C:\ myProject文件中, 而不是放在C:\ myProject \ src中。 然后使用:

文件文件=新文件(“test.txt”);

扫描仪输入=新扫描仪(文件);

要么

扫描仪输入=新扫描仪(新文件(“test.txt”));