2010-12-23 167 views
0

我有一個x行數的文本文件。每行保存一個整數。當用戶點擊一個按鈕時,通過actionlistener執行一個動作,它應該列出文本文件上顯示的所有值。但是,現在我已將亞麻布設置爲10,意味着我已經告訴代碼只能處理10行文本文件。所以,如果我的文本文件只有3行/行的數據...它會列出這些行,其餘7行,它會吐出「空」。使用java從文本文件中讀取數據行

我記得有一種方法可以使用省略號讓程序知道你不知道確切的值,但最後它會根據給定的信息來計算它。我給出的信息將包含數字(數據)的行數。

下面是代碼的一部分。

private class thehandler implements ActionListener{  
public void actionPerformed(ActionEvent event){ 
BufferedReader inputFile=null;   
try { 
    FileReader freader =new FileReader("Data.txt"); 
    inputFile = new BufferedReader(freader); 

    String MAP = ""; 
    int linenum=10; 
    while(linenum > 0) 
     { 
    linenum=linenum-1; 
    MAP = inputFile.readLine();//read the next line until the specfic line is found 

    System.out.println(MAP); 
    } 

    } catch(Exception y) { y.printStackTrace(); } 

}} 

回答

1

只是把代替linenum > 0下一行(MAP = inputFile.readLine()) != null 並刪除下一行,linenum=linenum-1; MAP = inputFile.readLine();下回有點谷歌搜索可以幫助+) 最後一行的空值將不被打印出來,因爲它設置該行是當前行並將其與空值進行比較,因此如果最後一行爲空,則不會打印它,10行限制如何?你可以做到這一點很容易,你只需添加一個索引來for循環和索引,並與& &檢查,如果我是較低的,然後10

+0

他會爲Google做什麼? – 2010-12-23 16:50:37

+0

使用文件?那我每次遇到問題時都會做什麼 – Swine1973 2010-12-23 17:06:19

0

你怎麼樣不打印地圖如果其值爲null?

1

測試是否回來從BufferedReader.readLine(),如果它是空停止循環,像這樣的值:

BufferedReader reader = new BufferedReader(new FileReader("Data.txt")); 
try { 
    for (String line; (line = reader.readLine()) != null;) { 
     System.out.println(line); 
    } 
} finally { 
    reader.close(); 
} 

編輯:忘了要求採取第10行,你可以改變上面的代碼把輸出的列表,並返回列表中,那麼你可以通過這樣的函數將其過濾:

public List<String> takeFirst(int howMany, List<String> lines) { 
return lines.size() <= howMany ? lines : lines.subList(0, howMany); 
} 

如果該文件是巨大的,那麼這將是低效的,當然,如果是重要的,你將結束做類似的事情:

BufferedReader reader = new BufferedReader(new FileReader("Data.txt")); 
try { 
    int linesRead = 0; 
    for (String line; (line = reader.readLine()) != null && linesRead < 10;) { 
     System.out.println(line); 
     linesRead += 1; 
    } 
} finally { 
    reader.close(); 
} 

這是醜陋的,但只讀取您需要的行。