2013-06-21 20 views
0

我不是開放試圖讀取與內容 一個簡單的文本文件input.txt中文件中的Java

Line 1 
Line 2 
Line 3 

但它總是轉到異常並顯示錯誤。

import java.io.*; 
import java.util.*; 

public class Main { 
    public static void main(String args[]){ 

     List<String> text = new ArrayList<String>(); 
     try{ 
      BufferedReader reader = new BufferedReader(new FileReader("input.txt")); 
      for (String line; (line = reader.readLine()) != null;) { 
       text.add(line); 
      } 
      System.out.println(text.size()); //print how many lines read in 
      reader.close(); 
     }catch(IOException e){ 
      System.out.println("ERROR"); 
     } 
    } 
} 

使用Eclipse作爲我的IDE,如果這有所作爲的話。我試過這個代碼http://www.compileonline.com/compile_java_online.php 它運行良好,爲什麼不運行在Eclipse中?

+4

嘗試打印出異常。然後你就會知道錯誤究竟是什麼。 – iamnotmaynard

+3

我猜'FileNotFoundException - 但是,你永遠不應該忽略異常本身。 –

+1

同意。可能的input.txt不在正確的文件夾中。 – Cogman

回答

1

給出完整的文件路徑,如"C:\\folder_name\\input.txt"或將input.txt放在eclipse項目的src目錄中。

+0

其src文件夾內已有,請嘗試使用完整文件路徑 – Edd

+0

如果txt文件位於src(classpath)內,則不需要完整路徑。嘗試使用e.printStackTrace()打印出異常。 –

+0

它說系統找不到指定的文件 – Edd

1
public class Main { 
    public static void main(String args[]){ 

     List<String> text = new ArrayList<String>(); 
     try{ 
      BufferedReader reader = new BufferedReader(
        new FileReader("input.txt")); //<< your problem is probably here, 
      //More than likely you have to supply a path the input file. 
      //Something like "C:\\mydir\\input.txt" 
      for (String line; (line = reader.readLine()) != null;) { 
       text.add(line); 
      } 
      System.out.println(text.size()); //print how many lines read in 
      reader.close(); 
     }catch(IOException e){ 
      System.out.println("ERROR"); //This tells you nothing. 
      System.out.println(e.getMessage()); //Do this 
      //or 
      e.printStackTrace(); //this or both 

     } 
    } 
} 
+0

有沒有辦法可以引用當前目錄? – Edd

+2

你在做什麼確實指的是當前目錄,但是我認爲這是你的問題。直到你有堆棧跟蹤,你不知道。 –

1

你很可能有一個不好的路徑。考慮這個主要代替:

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

     List<String> text = new ArrayList<String>(); 

     BufferedReader reader = new BufferedReader(new FileReader("input.txt")); 
     for (String line; (line = reader.readLine()) != null;) { 
      text.add(line); 
     } 
     System.out.println(text.size()); //print how many lines read in 
     reader.close(); 
    } 
} 

「拋出異常」此外允許您專注於代碼,並考慮更好的錯誤處理。另外考慮使用File f = new File("input.txt")並使用它,因爲它允許您打印出f.getAbsolutePath(),告訴你它實際上正在查找的文件名。

+1

您發佈的代碼不能編譯。 '公共類主要拋出異常{'是錯誤的,也許你在談論'公共靜態無效的主要(字符串參數[])拋出異常{'? – BackSlash

+0

我手動編輯原始帖子。謝謝。 –

0

input.txt更改爲src\\input.txt解決了問題! 我想這是因爲當前目錄實際上是其父母的src文件夾,

感謝您的幫助!

+1

當你只是說'輸入。txt「,那麼它將開始查看其根文件夾(您的src和其他項目相關文件夾所在的位置),這意味着您的項目文件夾。當你說'src \\ input.txt'意思是'根文件夾\ src \ input.txt'。 – Smit