【问题标题】:How to get my output to read from the text file? [duplicate]如何让我的输出从文本文件中读取? [复制]
【发布时间】:2020-04-24 17:39:31
【问题描述】:

我遇到了错误

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

        }

    }

}

【问题讨论】:

  • 你检查过文件是否真的存在吗?也许有错字什么的?
  • 另外,将文件存储到 C(或任何驱动器)的根目录中是一个非常糟糕的主意。创建一个子目录并将您的文件存储在那里。
  • C 的根目录通常受保护,需要管理员权限。

标签: java eclipse


【解决方案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");
       }

   }

} 

如果文件不存在,则检查该文件是否从该路径中丢失或文件名不匹配。

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 2016-07-06
    • 2021-02-20
    • 2018-05-03
    • 2013-06-01
    • 1970-01-01
    相关资源
    最近更新 更多