arsenal
arsenal

Reputation: 24184

create a text file in a folder

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..

Upvotes: 5

Views: 36309

Answers (4)

Wolf
Wolf

Reputation: 1001

your path-delimiter seems off

try:

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

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692171

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.

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

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

Upvotes: 1

hoipolloi
hoipolloi

Reputation: 8044

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

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

Upvotes: 6

adarshr
adarshr

Reputation: 62603

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).

Upvotes: 6

Related Questions