我的程序没有打开文本文件来阅读它

时间:2016-04-08 19:11:58

标签: java

我的代码无法读取

course.txt文件。它允许我输入文件名,但不打开文件。

my .txt file courses.txt

package javaexam;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.BufferedReader;
import java.util.Scanner;

public class BufferReader {
    public static void main(String[] args)  {
        Scanner scanner=new Scanner(System.in);
        BufferedReader bf = null; // shows warning that assigned but never used
        String line;
        System.out.println("Please enter the file name");      
        try { 
            bf = new BufferedReader(new FileReader("C:\\Users\\MohammedArfa\\Desktop\\New folder\\" + scanner.next()));
        } catch(FileNotFoundException fnfex) {
            //shows warning that the buffer assignment is declared but never used
            System.out.println(fnfex.getMessage()+"The file was not found"); 
        }
        System.exit(0);
        try {
            while((line=bf.readLine()) != null) {
                System.out.println(line);
            }
        } catch(IOException ex) {
            System.out.println(ex.getMessage()+"Error reading file");
        } finally {
            System.out.println(0);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

将system.exit(0)移动到上面的catch语句中......

 try { 
     bf = new BufferedReader(new        FileReader("C:\\Users\\MohammedArfa\\Desktop\\New folder\\" + scanner.next()));
 } catch(FileNotFoundException fnfex) {
      //shows warning that the buffer assignment is declared but never used
      System.out.println(fnfex.getMessage()+"The file was not found"); 
      System.exit(0);
 }

如果system.exit(0)不在catch中,那么它总是被执行,在你到达打印输出循环之前终止你的程序。