2012-03-11 174 views
16

我想使用相對路徑在新目錄中創建文件。創建目錄「tmp」很容易。Java - 如何使用相對路徑在目錄中創建文件

但是,當我創建文件時,它只位於當前目錄中,而不是新文件。代碼行如下。

File tempfile = new File("tempfile.txt"); 

試過這也:

File tempfile = new File("\\user.dir\\tmp\\tempfile.txt"); 

顯然我誤解這個方法是如何工作的。非常感謝您的幫助。

編輯:添加了當前使用的代碼行以及我認爲可能用於清除混淆的相對路徑。

+1

上面的代碼使用絕對路徑:'\ user.dir \ tmp \ tempfile.txt'。我沒有看到如何在當前目錄中創建該文件。發佈相關的代碼,向我們解釋你期望它做什麼,以及它做了什麼。 – 2012-03-11 19:50:33

+1

*「使用相對路徑。」*相對於什麼?應用程序?班級的包裹?相對論觀察者?請注意,a)這是一個構造函數,而不是一個方法。 b)'user.dir'不會自動擴展。 c)魔法編程很少有效,請嘗試閱讀文檔。 – 2012-03-11 19:53:27

回答

23
File dir = new File("tmp/test"); 
dir.mkdirs(); 
File tmp = new File(dir, "tmp.txt"); 
tmp.createNewFile(); 

BTW:爲了測試使用@rule和TemporaryFolder類來創建臨時文件或文件夾

+0

這樣做!謝謝,這需要花幾個小時才能找出我需要兩個單獨的新File語句。 – 2012-03-11 20:12:54

+3

就像你站起來一樣(因爲你可能不知道這一點),但Sun,呃Oracle有很好的API文檔。一旦你學會了解並瀏覽它們,它們可以節省很多時間。例如,如果您已經查看了File類的用戶可用的各種構造函數,則可以找出解決具體問題的方法:http://docs.oracle。COM/JavaSE的/ 6 /文檔/ API/JAVA/IO/File.html – claymore1977 2012-03-12 10:49:31

4

您可以創建兩個參數相對於與構造一個目錄路徑:http://docs.oracle.com/javase/6/docs/api/java/io/File.html

例如:

File tempfile = new File("user.dir/tmp", "tempfile.txt"); 

順便說一句,反斜槓「\」只能在Windows上使用。在幾乎所有情況下,您都可以使用便攜式正斜槓「/」。

+5

「File.separator」發生了什麼? – Manish 2012-03-11 19:56:48

+1

*「在幾乎所有情況下,您都應該使用便攜式正斜槓」/「。」*在每個***案例中,您應該使用接受「File」(父)&String的File構造函數'(文件名)或使用'System.getProperty(「file.separator」)''。 – 2012-03-11 19:57:31

+0

@Manish它應該是全部小寫。 – 2012-03-11 19:58:38

2
String routePath = this.getClass().getClassLoader().getResource(File.separator).getPath(); 
System.out.println(routePath); 

/*for finding the path*/ 
String newLine = System.getProperty("line.separator"); 
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(routePath+File.separator+".."+File.separator+"backup.txt"), true)); 
/*file name is backup.txt and this is working.*/ 
0

讓說你有「本地存儲」您的項目文件夾,你想放一個文本或任何文件使用文件寫入

File file = new File(dir,fileName); //KEY IS DIR ex."./local-storage/" and fileName='comp.html' 

     // if file doesnt exists, then create it 
     if (! file.exists()) 
     { 
      file.createNewFile(); 
     } 

     FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
     BufferedWriter bw = new BufferedWriter(fw); 
     bw.write(text); 
相關問題