2014-03-06 31 views
1

我已成功使用PrintWriter將字符串寫入文本文件,並且默認情況下會將輸出文本文件寫入正在處理的Eclipse項目的目錄中。Printwriter目標問題

但我的Eclipse項目已要求我想要的文本文件寫入到資源的特定文件夾:

我的代碼是:

protected void saveCommandsToFile() throws FileNotFoundException, IOException { 
    PrintWriter out = new PrintWriter("commands.txt"); 
    int listsize = list.getModel().getSize(); 
    for (int i=0; i<listsize; i++){ 
     Object item = list.getModel().getElementAt(i); 
     String command = (String)item; 
     System.out.println(command); //use console output for comparison 
     out.println(command); 
    } 
    out.close(); 
} 

如果我行更改爲:

PrintWriter out = new PrintWriter("/Resources/commands.txt"); 

正在拋出FileNotFoundException。我如何解決這個問題?謝謝!

回答

1

A PrintWriter創建這種方式會期望一條路徑,它可以是相對路徑或絕對路徑。

相對路徑是相對於工作目錄。

另一方面,絕對路徑需要包含根目錄(或多個目錄)的完整路徑,所以在Windows上它將類似c:/foo/bar.txt,在Unix類型系統/home/nobody/foo/bar.txt上。

絕對和相對路徑的確切規則可以找到here

雖然關於使用相對路徑的說明。當你依賴它們時要小心,因爲你無法知道你的工作目錄是什麼:當你從Eclipse運行應用程序時,它將默認爲你的項目目錄,但是如果你打包並運行命令行,它會在別的地方。

即使您只是從Eclipse運行它,寫在您的項目文件夾不是最好的想法。不僅可能無意中覆蓋源代碼,而且代碼也不會很輕便,如果稍後決定將所有東西打包到jar文件中,則會發現無法找到這些目錄任何更多(因爲他們都打包)。

0

您指定的路徑是絕對路徑。如果你想讓它與你正在運行java程序的地方相關,請嘗試使用"./Resources/commands.txt"

替代方案,您可以使用項目文件夾的完整路徑。

1

試試下面的代碼:

protected static void saveCommandsToFile() throws FileNotFoundException, IOException { 
    File file = new File("resources/commands.txt"); 
    System.out.println("Absolute path:" + file.getAbsolutePath()); 
    if (!file.exists()) { 
     if (file.createNewFile()) { 
      PrintWriter out = new PrintWriter(file); 
      out.println("hi"); 
      out.close(); 
     } 
    } 
} 

下面是該項目的文件夾結構:

Project 
| 
|___src 
| 
|___resources 
    | 
    |___commands.txt