2013-04-03 16 views
-2

如果我想爲某個類構建一個構造函數來導入一個文件,該文件已在字符串nameOfFile中傳遞,那麼如何初始化該對象的狀態,然後打開文檔文件並處理每行該文件?參考和明確的解釋將不勝感激。我剛開始學習java。用於導入文件的構造函數

要清除我的問題,如何爲您導入的文檔文件構建一個對象?我現在正在做的是我寫了一個類,但我正在努力爲一個特定文件構建一個對象。我到目前爲止是

public class theImport 
{ 

theImport(String nameOfFile) 
{ 
(Here is where I want to achieve all the listing I have above.) 
} 
. 
. 
. 
} 
+1

你說的意思是「初始化對象的什麼狀態「? 通過調用構造函數,您正在初始化obj等。 – 2013-04-03 20:36:47

+2

通過在文件中添加一些示例數據和[SSCCE](http://sscce.org/),您可以更好地提出問題,以證明您試圖實現的目標。否則,它看起來像你在這裏複製粘貼(家庭作業)的問題,要求一個完整的解決方案。 – 2013-04-03 20:40:38

回答

1

我相信你會在兩步過程中做到這一點。

第一步:實際的構造函數。

private String nOF; 
public ClassName(String nameOfFile) { 
    nOF = nameOfFile; 
} 

第二步:評估文件。由於這可能由於各種原因而失敗(例如文件不存在,它不應該去構造函數中(你不能從構造函數中沒有的返回類型中捕獲這些錯誤)

public boolean Evaluate() { 
    //Evaluate your file and return false if it fails for whatever reason. 
} 

我的Java不是目前最好的,但這應該提示你在正確的方向

0

Propably你的意思是這樣的:

public class theImport 
    { 

      theImport(String nameOfFile) 
      { 
      try { 
        FileReader input = new FileReader(nameOfFile); 
        BufferedReader bufRead = new BufferedReader(input); 
        String line; 
        line = bufRead.readLine(); 
        //this will loop thought the lines of the file 
        while (line != null){ 
          line = bufRead.readLine(); 
          //do whatever you want with the line 
        } 
        bufRead.close(); 
      }   
      catch (Exception e){ 
        e.printStackTrace(); 

      } 
     } 
    }