2013-12-09 41 views
-2

這裏我有一個IO問題。字符串ext []只讀取txt文件的最後一個條目,在這種情況下只有jpg。 我想讀所有,但它只有最後我要保持這種代碼在構造 事先請指出錯誤 感謝讀取讀取數組中的文件java

/////Text file format 
     txt 
     png 
     jpg 

    ///// file reading code 

String line; 
//// constructor 
    public MainFrame(){ 
    initComponents(); 
    fileChooser=new JFileChooser(); 
    try { 
    Scanner in = new Scanner(new FileReader("ext.txt")); 
    while (in.hasNextLine()) { 
      line = in.nextLine(); 
     } System.out.println(line); 
      String ext[] = line.split("\\n"); /// can't read all the strings from file. 

    FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES",ext); 
    fileChooser.setFileFilter(filter);} 
    catch(IOException io){ 

    } 
    } 
+1

檢查括號..... – Blub

+2

你的右大括號後應'line.split( 「\\ N」);' –

+0

沒有在那裏,我有字符串在正確位置和變量範圍上的問題 – user3078848

回答

1

你的問題是與String ext[]

每次通過循環覆蓋變量ext[]。我想,而不是你應該做的:

try { 
ArrayList<String> ext = new ArrayList<String>(); 
Scanner in = new Scanner(new FileReader("ext.txt")); 
while (in.hasNextLine()) { 
     line = in.nextLine(); 
    } System.out.println(line); 
     ext.append(line.split("\\n")); 

您可能必須做一些語法的工作,因爲我還沒有在Java中了一點工作,但我認爲這是正確的

+0

我只需要字符串var,因爲FIleNamefilter方法只支持字符串var。 – user3078848

+0

感謝您的幫助 但我是通過簡單的字符串連接功能完成的。 ///////////////////// while(in.hasNextLine()){ line = in.nextLine(); line2 = line2 + = line +「\ n」; – user3078848

+0

@ user3078848啊你好,你不想把你的字符串放入數組中,而是一個長字符串? –

0

在讀取文件一行一行java通常使用BufferedReader完成。所以你也可以處理異常,你總是在閱讀後關閉文件。

下面是一個例子,但我強烈建議您閱讀有關使用文件的更多信息。一個很好的開始是Oracle文檔(http://docs.oracle.com/javase/tutorial/essential/io/file.html

//a collection that stores the lines 
List<String> lines = new ArrayList<String>() 
BufferedReader buf = null; 
try{ 
    buf = new BufferedReader(new FileReader(file)); 
    String line = null; 

    while((line = buf.readLine()) != null){ 
     lines.add(line); 
    } 
//if something goes wrong 
catch(IOException ex){ 
    ex.printStackTrace(); 
} 
finally{ 
    //closing the buffer, so that the file isnt locked anymore 
    if(buf != null) 
     buf.close(); 

}