Reputation: 65
This doesn't seem to create a file or folder. Why?
import java.io.*;
public class file1
{
public static void main(String[] args)
{
File text1 = new File("C:/text1.txt");
File dir1 = new File("C:/dir");
}
This one below does create a file.
import java.io.*;
public class file3
{
public static void main(String[] args)
{
try
{
FileWriter text1 = new FileWriter("C:/text.txt");
FileWriter dir = new FileWriter("C:/dir");
}
catch(Exception e){}
}
}
However, the directory seems to have a strange unusable icon.
What can I do to create a directory. What are other simple methods to create files and folders.
Upvotes: 2
Views: 116
Reputation: 718708
Surprisingly, the File
class does not represent a file. It actually represents a pathname for a file ... that may or may not exist.
To create a file in Java, you need to open it for output; e.g.
File text1 = new File("C:/text1.txt");
FileOutputStream os = new FileOutputStream(text1); // The file is created
// here ... if it doesn't
// exist already.
// then write to the file and close it.
or you could do this - new FileOutputStream("C:/text1.txt")
. In both cases, an existing file will be truncated ... unless you use the FileOutputStream
with a boolean parameter that says open for appending.
If you want to create a file without writing any data to it, you could also do this:
File text1 = new File("C:/text1.txt");
text1.createNewFile();
However, that will only create a new file if the file didn't already exist.
To create a directory in Java, use the File.mkdir()
or File.mkdirs()
methods.
UPDATE
You commented:
I tried
File dir = new File("C:/dir1").mkdir();
it says incompatible types.
That is right. The mkdir()
method returns a boolean
to say whether or not it created the directory. What you need to write is something like this:
File dir = new File("C:/dir1");
if (dir.mkdir()) {
System.out.println("I created it");
}
Always READ THE JAVADOCS before using a method or class you are not familiar with!
A couple more things you need to know:
The best way to deal with the problem of making sure a file gets closed is to do something like this:
try (FileOutputStream os = new FileOutputStream(text1)) {
// now write to it
}
The stream os
will be closed automatically when the block exits.
It is usually "bad practice" to catch Exception
. It is always "bad practice" to catch Exception
and do nothing in the handler. This kind of this hides the evidence of bugs, and makes your code unpredictable and hard to debug.
Upvotes: 2
Reputation: 10994
For creating directory you can use :
if(!text1.exists()){
text1.mkdir();
}
and for creating file use:
if(!text1.exists()){
try {
text1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 0
Reputation: 8815
If you're creating a directory with File
, you want this:
new File("C:/dir").mkdirs();
Upvotes: 0