The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs()
.
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
With Java 7, you can use Path
, Paths
, and Files
:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With