在文件夹中创建一个文本文件。

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");

但是这段代码并不会在那个文件夹中创建文本文件,而是会在该文件夹外创建文本文件。
4个回答

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的文件,因为在字符串字面值中使用\"表示双引号字符,而不是反斜杠。必须使用\\来表示反斜杠。

使用以文件(目录)作为第一个参数,文件名作为第二个参数的File构造函数:

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

0

你的路径分隔符似乎有误

尝试:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接