如何使我的输出从文本文件读取?

我遇到一个错误

java.io.FileNotFoundException: C:\courses2.txt (The system cannot find the file specified)

检查了c驱动器并且路径正确,但是由于某种原因我没有得到输出。

我得到的最多是教师退回的副本,无法读取文件。

我的输出应显示课程代码,课程学时和课程标题

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class courses

{

    public static void main(String[] args) throws Exception

    {

        try {

            File file = new File("C:\\courses2.txt");

            BufferedReader br = new BufferedReader(new FileReader(file));

            String courseCode = "";

            String creditHours = "";

            String courseTitle = "";

            String st;

            System.out.println("Teacher's Copy");

            while ((st = br.readLine()) != null) {

                courseCode = st.substring(0, st.indexOf(" "));

                creditHours = st.substring(6, 8);

                courseTitle = st.substring(9);

                System.out.print("Course code = " + courseCode + " | ");

                System.out.print("Course credit hours = " + creditHours + " | ");

                System.out.print("Course Title = " + courseTitle);

                System.out.println();

            }

        } catch (Exception ex) {

            System.out.println(ex);

        }

    }

}
评论
  • xet
    xet 回复

    首先编写一个简单的代码来检查文件是否存在。

    代码:

    public class Test {
    
       public static void main(String...args) {
           File file = new File("C:\\courses2.txt");
           if(file.exists()) {
               System.out.println("File exists");
           } else {
               System.out.println("File doesn't exist");
           }
    
       }
    
    } 
    

    然后,执行所需的操作。