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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6656565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 12:24:06  来源:igfitidea点击:

create a text file in a folder

javafile

提问by arsenal

I want to create a text file into that folder that I am creating here.

我想在我在这里创建的那个文件夹中创建一个文本文件。

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

But this code doesn't create the text file into that folder..Instead it makes the text file outside that folder..

但是此代码不会将文本文件创建到该文件夹​​中。相反,它使文本文件位于该文件夹之外。

采纳答案by hoipolloi

One of java.io.File's constructors takes a parent directory. You can do this instead:

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

回答by adarshr

What you need is

你需要的是

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

The key here is the File(File parent, String child)constructor. It creates a file with the specified name under the provided parent directory (provided that directory exists, of course).

这里的关键是File(File parent, String child)构造函数。它在提供的父目录下创建一个具有指定名称的文件(当然,前提是该目录存在)。

回答by JB Nizet

The line

线

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

makes a file named crawl_html"the_hash.txt, because \"inside a String literal is used to represent a double quote caracter, not a backslash. \\must be used to represent a backslash.

生成一个名为 的文件crawl_html"the_hash.txt,因为\"在字符串文字内部用于表示双引号字符,而不是反斜杠。\\必须用于表示反斜杠。

Use the File constructor taking a File (directory) as the first argument, and a file name as a second argument:

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

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

回答by Wolf

your path-delimiter seems off

你的路径分隔符似乎关闭

try:

尝试:

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