cmc*_*els 4 java filenotfoundexception
我正在创建一个小程序,它将读取一个文本文件,其中包含大量随机生成的数字,并生成统计数据,如均值,中位数和模式.我创建了文本文件,并确保在声明为新文件时名称完全相同.
是的,该文件与类文件位于同一文件夹中.
public class GradeStats {
public static void main(String[] args){
ListCreator lc = new ListCreator(); //create ListCreator object
lc.getGrades(); //start the grade listing process
try{
File gradeList = new File("C:/Users/Casi/IdeaProjects/GradeStats/GradeList");
FileReader fr = new FileReader(gradeList);
BufferedReader bf = new BufferedReader(fr);
String line;
while ((line = bf.readLine()) != null){
System.out.println(line);
}
bf.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
}
错误行内容如下:
java.io.FileNotFoundException: GradeList.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at ListCreator.getGrades(ListCreator.java:17)
at GradeStats.main(GradeStats.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Run Code Online (Sandbox Code Playgroud)
nuz*_*uzz 10
如何添加:
String curDir = System.getProperty("user.dir");
Run Code Online (Sandbox Code Playgroud)
打印出来.它会告诉你当前的工作目录是什么.然后你应该能够看到它为什么找不到文件.
如果找不到文件,您可以检查以允许自己做某事,而不是允许您的代码抛出:
File GradeList = new File("GradeList.txt");
if(!GradeList.exists()) {
System.out.println("Failed to find file");
//do something
}
Run Code Online (Sandbox Code Playgroud)
请运行以下内容并粘贴输出:
String curDir = System.getProperty("user.dir");
File GradeList = new File("GradeList.txt");
System.out.println("Current sys dir: " + curDir);
System.out.println("Current abs dir: " + GradeList.getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28308 次 |
| 最近记录: |