无法在java中编写txt文件

问题描述:

我正在研究一项功能,使用户能够检查单个学生的评估结果。我使用try和catch,但是当我运行代码时,系统直接运行到catch部分,并且文件的内容是空白的。我不确定这个问题的原因。这里是我的代码:无法在java中编写txt文件

System.out.println('\n' + "Please enter the Student's uni that you would like to call. Type 'exit' to leave"); 
     String studentInfo = s.nextLine(); 
     if (studentInfo.equalsIgnoreCase("exit")) { 
     userSelection = "exit"; 
             } 

     boolean studentFound = false; 
     for (int i = 0; i < students.size(); i++) { 

     if (studentInfo.equalsIgnoreCase(students.get(i).getStudentUI())) { 
     studentFound = true; 

     try { 
      File singleStudentList = new File(studentInfo + " .txt"); 
      PrintWriter writer = new PrintWriter(singleStudentList); 

      System.out.println(studentUniLists.get(i)); 

      writer.println(studentUniLists.get(students.indexOf(studentInfo))); 
      writer.close(); 
      } catch (Exception e) { 
      System.out.println("Problem writing the file. Please make sure the path is correct"); 
      } 

      } 
     } 

感谢您的帮助!

+8

您不打印出异常消息! e.printStackTrace()。打印出来,编辑问题,并显示堆栈跟踪。 – OldProgrammer

+0

如果您的代码正在直接进入catch,那么问题可能出在File或PrintWriter的构造函数之一上。查看文档以查看它们抛出的特定异常:https://docs.oracle.com/javase/8/docs/api/java/io/File.html#File-java.lang.String- https: //docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html#PrintWriter-java.io.File- 据我的经验,问题可能是你试图打开的文件doesn 't exists – Antiphon0x

+0

使用'System.out.println(singleStudentList.getCanonicalPath())'来显示它正在尝试使用的文件路径。有可能你的程序没有在正确的目录中查找。 –

我的直觉是你的错误是在这两行之一:

 System.out.println(studentUniLists.get(i)); 

    writer.println(studentUniLists.get(students.indexOf(studentInfo))); 

您还没有包含的代码为studentUniLists是什么,所以这里的一些猜测。

我的猜测是students.indexOf(studentInfo)可能会返回-1,所以当你在List上做studentUniLists.get(-1)时,这会给你一个IndexOutOfBoundsException。你真的应该只捕捉IOException,这样就可以检测的地方这种问题

指数可能出界,e.g:

System.out.println(studentUniLists.get(i)); 

确定studentUniLists有指标吗? 由于你写的没有输出,它只是直接捕捉。

正如其他地方所评论的,打印实际的异常有帮助。

您发现任何异常,并向控制台打印这是与文件相关的问题。它不一定是。 我建议你加入你的catch子句e.printStackTrace()来打印真正的问题。其次,您应该考虑避免捕捉异常,因为它太宽泛。可能值得捕捉与文件问题有关的异常,并使其余的未被捕获。

查看文档 - PrintWriter不会引发错误。 Comstructor可能会抛出FileNotFoundException或SecurityException。 CheckErrors是您检查文件相关错误所需的功能。 https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#checkError()。但我相信你有非文件相关的问题,如NullPointerException或IndexOutOfBoundsException。

希望这会有所帮助。

首先,使用JDK 1.7,当您打开该文件使用尝试ressources让JVM做密切的全自动。 新的文件(studentInfo + “.TXT”) 你总是创建空文件“真.TXT”

File singleStudentList; 

try (singleStudentList = new File(studentInfo + " .txt")) {   

     PrintWriter writer = new PrintWriter(singleStudentList); 

} 

其次,错误是由这个越来越三,打印错误ex.printStackTrace();