java - java写入txt文件失败

标签 java

我正在开发一个功能,使用户能够检查单个学生的评估结果。我使用try和catch,但是当我运行代码时,系统直接运行到catch部分,并且文件内容为空。我不确定这个问题的原因。这是我的代码:

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");
            }

           }
        }

感谢您的帮助!

最佳答案

我的预感是您的错误出在这两行之一:

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

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

您还没有包含有关 StudentUniLists 是什么的代码,因此这里有一些猜测。

我的猜测是,students.indexOf(studentInfo) 可能会返回 -1,因此当您在 List 上执行 StudentUniLists.get(-1) 时,这将为您提供一个 IndexOutOfBoundsException。您实际上应该只捕获IOException,以便您可以检测此类问题

关于java - java写入txt文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41307912/

相关文章:

java - 在两个 WAR 之间共享应用程序上下文?

java - Java Web 应用程序和 C++ 服务器之间的套接字通信

java - 基本字符串操作,删除 While 循环中的最后一个字符

java在eclipse中导入代码的问题

java - @Repository dao 中的 Spring @PostConstruct 和扩展 dao 的 @Service

java - 在 Java 中是否有并行调用多个函数的简写方式?

java - 将 certificate.pfx 导入到 cacerts 中,但仍然出现 "PKIX...unable to find valid certification path to requested target"错误。做什么?

java - 在 JAVA 中验证多个字段的最佳方法?

java - 当超过此主体的最大 session 数时,Spring 安全重定向

java - 如何在没有任何外部依赖的情况下从 java 应用程序调用 php Web 服务?