2017-09-28 58 views
-2

这里没有粘贴整个代码,该行是:的PrintWriter:java.io.FileNotFoundException:在异常情况持续发生,系统找不到指定的路径

PrintWriter prtwrt = new PrintWriter(new File(directoryName+File.separator+stud.getIndex()+".txt")); 

我已经咨询了互联网和书籍我对Java有所了解,并且应该遵循所有逻辑工作,但事实并非如此。有人可以解释为什么它不起作用,或者可能提出解决方案吗?

堆栈跟踪:

java.io.FileNotFoundException: students\0096-03.txt (The system cannot find the path specified) 
    at java.io.FileOutputStream.open0(Native Method) 
    at java.io.FileOutputStream.open(Unknown Source) 
    at java.io.FileOutputStream.<init>(Unknown Source) 
    at java.io.FileOutputStream.<init>(Unknown Source) 
    at java.io.FileWriter.<init>(Unknown Source) 
    at StudentsManager.main(StudentsManager.java:47) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267) 

此外,目录名,顾名思义,是该文件应该创建目录的名称。在这种情况下,它是“学生”。

+3

什么是'directoryName'?也可以使用堆栈跟踪粘贴整个异常 – Antoniossss

+0

它不起作用,因为系统找不到指定的路径。 – Oleg

+0

@Antoniossss编辑了问题 –

回答

0

尝试输入文件的完整路径,因为您可能会输入相对路径。

如果你想检查是否已找到该文件试试下面的代码:

File file = new File(...); 
if(!file.exists()) { 
    System.out.println("File not found!"); 
    return; 
} 
0

所以让有

File f=new File(directoryName+File.separator+stud.getIndex()+".txt"); 

首先让检查,如果路径存在,如果它创建目录树没有:

if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); 

现在你可以尝试创建作家

PrintWriter prtwrt = new PrintWriter(f); 

PrintWriter如果还不存在,应该创建新文件;如果因为某些原因无法正常工作,请在创建文件之前使用f.createNewFile()

总而言之,它必须工作。

相关问题