2011-07-11 136 views
5

我想在這裏創建的文件夾中創建一個文本文件。在一個文件夾中創建一個文本文件

File dir = new File("crawl_html"); 
dir.mkdir(); 
String hash = MD5Util.md5Hex(url1.toString()); 
System.out.println("hash:-" + hash); 
File file = new File(""+dir+"\""+hash+".txt"); 

但這代碼不創建文本文件到該folder..Instead它使該文件夾以外的文本文件..

回答

6

java.io.File的構造函數之一需要父目錄。因爲\"文本字符串中用來表示一個雙引號卡拉科特,而不是一個反斜槓

final File parentDir = new File("crawl_html"); 
parentDir.mkdir(); 
final String hash = "abc"; 
final String fileName = hash + ".txt"; 
final File file = new File(parentDir, fileName); 
file.createNewFile(); // Creates file crawl_html/abc.txt 
6

你需要的是

File file = new File(dir, hash + ".txt"); 

的關鍵這裏是File(File parent, String child)構造函數。它會在提供的父目錄下創建一個具有指定名稱的文件(當然,前提是該目錄存在)。

1

new File(""+dir+"\""+hash+".txt"); 

使名爲crawl_html"the_hash.txt文件:你可以做到這一點吧。必須使用\\來表示反斜槓。

使用文件的構造以文件(目錄)作爲第一個參數和文件名作爲第二個參數:

new File(dir, hash + ".txt"); 
0

您的路徑分隔符似乎離

嘗試:

File file = new File ("" + dir + "/" + hash + ".txt"); 
相關問題