2013-06-05 45 views
0

首先,我對Java仍然很不喜歡,所以我想這可以很容易地回答。Buffered Reader和Filepaths - Easy

我有一個程序,首次啓動時,如果該文件不存在,將在指定位置(C盤上的AppData文件夾)中查找名爲location.txt的文件,則會創建該文件。該文件最終只會有一個從JFileChooser中選擇的文件路徑。

我想讓我的程序讀取此文本文件中的文件路徑,以便我不必靜態引用文件位置。不過,我現在有一個問題。下面是一些代碼:(不介意窮人碼間距,計算器正在爲難我)

BufferedReader bufferedReader = new BufferedReader(fileReader); // creates the buffered reader for the file 
    java.util.List<String> lines = new ArrayList<String>(); //sets up an ArrayList (dynamic no set length) 
    String line = null; 
    try { 
     while ((line = bufferedReader.readLine()) != null) {  // reads the file into the ArrayList line by line 
      lines.add(line); 
     } 
    } catch (IOException e) { 
     JOptionPane.showMessageDialog(null, "Error 16: "+e.getMessage()+"\nPlease contact Shane for assistance."); 
     System.exit(1); 
    } 
    try { 
     bufferedReader.close();    
    } catch (IOException e) { 
     JOptionPane.showMessageDialog(null, "Error 17: "+e.getMessage()+"\nPlease contact Shane for assistance."); 
     System.exit(1); 
    } 

    String[] specifiedLocation = lines.toArray(new String[lines.size()]); // Converts the ArrayList into an Array. 

    String htmlFilePath = specifiedLocation + "\\Timeline.html"; 
    File htmlFile = new File(htmlFilePath); 

    JOptionPane.showMessageDialog(null, specifiedLocation); 
    JOptionPane.showMessageDialog(null, htmlFilePath); 

我不明白是爲什麼,當指定位置的消息對話框彈出時,文件路徑那裏是完美的。然而,當該htmlFilePath消息對話框彈出,它看起來像這樣:

[Ljava.lang.String; @ 1113708 \ Timeline.html

任何幫助是非常感謝!

編輯: 我想通了.. 砰的一聲在桌子上我試圖讓它看看一個數組,而不是指定哪一個。錯誤的代碼練習,我知道,但簡單的修復是採取這個:

String htmlFilePath = specifiedLocation +「\ Timeline.html」;

字符串htmlFilePath = specifiedLocation [0] + 「\ Timeline.html」;

很抱歉的愚蠢帖子...

回答

4

Array S中toString方法不overrided。它會返回一個String陣列表示(這是Object中的toString),它包括對象(數組)的類型+「@」+其哈希碼。

如果您希望輸出效果更好,請改用Arrays.toString。但是,這仍然給你[ s,所以基於循環的ad-hoc解決方案可能會更好。另外,如果連接String s,則使用StringBuilder可以更快。

另外see(無恥促銷)我對另一個問題的回答。

+0

爲什麼會出現'的String []'正確顯示在第一次調用'showMessageDialog' –

0

替換此

String htmlFilePath = specifiedLocation + "\\Timeline.html"; 

StringBuilder htmlFilePath= new StringBuilder(); 
    for(String s : specifiedLocation) 
     htmlFilePath.append(s) ; 
    htmlFilePath.append("\\Timeline.html"); 

您還可以使用Arrays.toString(specifiedLocation)More info