如何让我的输出从文本文件中读取?[重复]

问题描述 投票:0回答:1

我遇到了一个错误

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

        }

    }

}
java eclipse
1个回答
1
投票

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

代码 :

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

   }

} 

如果文件不存在,则检查该文件是否从该路径中缺失或发生文件名不匹配的情况。

© www.soinside.com 2019 - 2024. All rights reserved.