I was just wondering if the code I made will work to create multiple directories within each other. I used this as a reference.
String username = enterUserTF.getText(); //the username the user enters in a textfield.
boolean myGamesFolderSuccess = new File(System.getProperty("user.home"), "My Games").mkdir();
boolean mainFolderSuccess = new File("My Games", "Type King").mkdir();
boolean userSuccess = new File("TypeKing", username).mkdir(); //creates a folder with the users username.
if(myGamesFolderSuccess){
if(mainFolderSuccess){
if(userSuccess){
System.out.println("Directory " + username + " created.");
File f = new File(username + "/test.txt");
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not create user's file.");
}
}
}
}
}
}
So to sum up the above, I made the the first directory "My Games" in user.home, then placed my game's name, "Type King" in that directory, and whenever the user enters a username, I want a directory to be created that is their username. File f just checks for a file in the username directory.
It is recommended to use the mkdirs method of the File class instead of checking multiple status flags when creating nested directories. Also, never use concatenation for creating File objects/paths.
Also, if you want your game to be portable, make sure you don't have special characters in your directory names like a space etc.Why are you asking user for the name instead of retrieving it from user.name system property? Something like this should work:
String username = System.getProperty("user.name");
File myGamesDir = new File(System.getProperty("user.home"), "my-games");
File typeKingDir = new File(myGamesDir, "type-king");
File userDir = new File(typeKingDir, username);
boolean userSuccess = userDir.mkdirs();
if(userSuccess){
System.out.println("Directory " + username + " created.");
File f = new File(userDir, "test.txt");
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not create user's file.");
}
}
}
If you pass a full path to File.mkdirs (with an s) it will make an arbitrarily deep directory structure. You don't have to build paths one directory at a time. If the directories already exist, or if some of them exist, it will still work as you expect.
import java.io.File;
import javax.swing.JOptionPane;
class Dirs {
public static void main(String[] args) throws Exception {
String subDir = "My Games|Type King";
String userName = JOptionPane.showInputDialog(
null,
"Who are you?");
subDir += "|" + userName;
String[] parts = subDir.split("\\|");
File f = new File(System.getProperty("user.home"));
for (String part : parts) {
f = new File(f, part);
}
boolean madeDir = f.mkdirs();
System.out.println("Created new dir: \t" + madeDir + " \t" + f);
f = new File(f, "eg.txt");
if (!f.exists()) {
boolean madeFile = f.createNewFile();
System.out.println(
"Created new file: \t" + madeFile + " \t" + f );
}
}
}
Output
Created new dir: true C:\Users\Andrew\My Games\Type King\BilboBaggins
Created new file: true C:\Users\Andrew\My Games\Type King\BilboBaggins\eg.txt
I think its better to use existing functionality available in the API. If you don't have any restrictions consider switching to the latest JDK. In 1.7 Oracle did introduce so many enhancements including IO and New IO.
For creating multiple directories within each other you can take advantage of Files.createDirectories available since 1.7. "It will create a directory by creating all nonexistent parent directories first."
Related
I need some help in picking the exact file from directory on Windows using Java. Below is the code which I have written for this. But when I pass my input as "XYZ" file it always picks the "ABC" file only.
My input to pick the file was 'XYZ', but output always returns 'ABC' file
directoryPath = new File(System.getProperty("user.dir") + "\\TestFilesDirectory\\");
String contents[] = directoryPath.list();
System.out.println("List of files and directories in the specified directory : " + directoryPath);
for (int i = 0; i < contents.length; i++) {
// System.out.println(contents[i]);
ArrayList<String> fileNameList = new ArrayList<String>();
String[] fileNameSplit = contents[i].split("_");
for (int k = 0; k < fileNameSplit.length; k++) {
// System.out.println(fileNameSplit[k].toUpperCase());
fileNameList.add(fileNameSplit[k].toUpperCase());
}
if (fileNameList.contains("ABC") {
System.out.println("Pick ABC file from directory ");
source = new File(directoryPath + "\\" + contents[i] + "");
}
System.out.println("Base File: " + source);
else if (fileNameList.contains("DEF") {
System.out.println("Pick DEF file from directory ");
source = new File(directoryPath + "\\" + contents[i] + "");
}
else if (fileNameList.contains("XYZ") {
System.out.println("Pick XYZ file from directory ");
source = new File(directoryPath + "\\" + contents[i] + "");
}
Below are my files in Test directory:
I think that your code can be improved. As far as I can tell you need to retrieve the path of a given file matching either the first or second part of its filename. So for example:
DEF_GHI.txt
can be matched by either inputting def or ghi into your search method. The easiest and most concise way to do so would be:
public Optional<File> findByName(String name, String directoryPath) {
try (var fileStream = Files.list(Path.of(directoryPath))) {
return fileStream
.filter(path -> Arrays.stream(path.getFileName().toString().split("_"))
.map(part -> part.replaceAll("\\.[^.]*$", ""))
.anyMatch(part -> part.equalsIgnoreCase(name)))
.findAny()
.map(Path::toFile);
} catch (IOException e) {
System.err.println("Unable to open directory stream for path:: " + directoryPath);
e.printStackTrace();
}
return Optional.empty();
}
What this does is the following:
Accepts a filename and a path representing a directory to search at
Creates a stream of paths representing the files under the given directory
Gets the filename for each given path and performs the following:
Splits the string using _ in order to retrieve both parts (if present)
Replaces everything after the . character (including it) in order to get rid of the file extension.
Attempts to match each part against the provided name parameter
Map the found path value to a File (if present)
Lastly returns either the optionally wrapped File or an empty Optional.
I hope this is what you are looking for.
How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
So i'm working on a simple Windows Explorer replacement. I want to add the ability to create Folders and Files. For some reason, it only works when i'm in my root or c:/ folder, but as soon as it's somewhere else (for example C:\Program Files (x86)) it doesn't work. I either get a java.io.IOException: Access Denied when i create a File and when i try to create a folder, no Exception comes up, but no folder is created.
This is my code for a new file:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new file. \nDon't forget to add file type (.txt, .pdf).", null);
if(name == null){
}
else {
File newFile = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFile.createNewFile();
} catch (IOException Io) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "File creation failed with the following reason: \n" + Io);
}
}
This is my code for a new Folder:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new folder.", null);
if(name == null){
}
else {
File newFolder = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFolder.mkdir();
} catch (SecurityException Se) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "Folder creation failed with the following reason: \n" + Se);
}
}
I'm stuck right now and i have no idea what i'm doing wrong to get rid of the access denied error.
Short explenation of how this program works:
My program shows a list of all folders and files from a selected File.
That File is a field in the class JXploreFile called "currentFile", which behaves almost the same as a File.
When browsing through the folders, the currentFile is set to a new JXploreFile, containing the new folder you are in as File.
When creating a new folder/file, my program ask the path the user is currently browsing in with the method getPath().
Thanks for the help!
Image of my program:
Before you try to make any I/O operation just check if you have the permission
go to the parent directory (your case location)
then do something like
File f = new File(location);
if(f.canWrite()) {
/*your full folder creation code here */
} else {
}
try to put
String location ="c:\\user\<<youruser>>\\my documents"
or a folder with full perission to write
import java.io.File;
class AttriDemo{
public static void main(String args[]){
File f1 = new File("FileIO/file.txt");
System.out.println("File name : " + f1.getName());
System.out.println("File path : " + f1.getPath());
System.out.println("File AbsPath : " + f1.getAbsolutePath());
System.out.println("File parent : " + f1.getParent());
f1.setWritable(true);
if(f1.canWrite())
{
System.out.println("File is Writeable");
}
else
{
System.out.println("File is not Writeable");
}
if(f1.canRead())
{
System.out.println("Is readable");
}
else
{
System.out.println("File is not readable");
}
}
}
I the file is readable and writable in real...
then I tried setting it to Writable explicitly but still the output shows it as the file is not writable!!
output:
....
The file is not writable.
The file is not readable.
File f1 = new File("D:/javaProgs/FileIO/AttriDemo.java");
doing this helps solve the problem.
but can someone explain how? I mean the file was in the same directory and the statements above were running just fine. e.g getName() getParent()
What's fooling you is you can create a File object regardless of the path you specified exists or not and you can call all those getParent, getPath functions on that object.
You can create a File object that's not backed by a real file for various reasons like to check if it exists or to create a file specified by that objects path and name.
You can use File.exists() to see if file really exists on file system.