2016-04-08 70 views
0

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

你有什麼錯誤嗎? –

+3

你應該真的處理你的代碼格式。然後你會在你的代碼中看到這個***非常錯誤的***'System.exit(0);'。下次再多加小心。投票結束,因爲看起來像一個「大」的錯字(因爲這個'System.exit(0)'在那裏看起來不需要)。 – Tom

+0

沒有錯誤,但沒有顯示文件的內容 – arfa

回答

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)不是抓內部則總是在你到達打印輸出循環之前終止你的程序。