Java create directory in linux

Create a folder and a file with Java in Ubuntu

Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn’t create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code:

File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) < >else < folder.mkdir(); >String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here 

Please, accept one of the following answer if your question is fulfilled (even if it’s not mine, obviously)

7 Answers 7

Linux does not use drive letters (like D:) and uses forward slashes as file separator.

You can do something like this:

File folder = new File("/path/name/of/the/folder"); folder.mkdirs(); // this will also create parent directories if necessary File file = new File(folder, "filename"); StreamResult result = new StreamResult(file); 

You directory (D:\temp) is nos appropriate on Linux.

Please, consider using linux File System, and the File.SEPARATOR constant :

static String OS = System.getProperty("OS.name").toLowerCase(); String root = "/tmp"; if (OS.indexOf("win") >= 0) < root="D:\\temp"; >else < root="/"; >File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2"); if (folder.exists() && folder.isDirectory()) < >else

Didn’t tried it, but whould work.

Читайте также:  Таблица

Nope. If you create a folder to D:\something linux creates a folder named D:\something in your user directory (tried it)

I will be more accurate, but I meany «D:\temp», I didn’t see Shase doubled it. You’re right it works, I always complain about my colleagues that left thos kind of path in log4j configuration 🙂

root=»/»; It not good solution because not each user can write to root . More correct write to /tmp or home directory.

D:\temp does not exists in linux systems (what I mean is it interprets it as if it were any other foldername)

In Linux systems the file seperator is / instead of \ as in case of Windows

File folder = new File("D:\\temp"); 

Nope. If you create a folder to D:\something linux creates a folder named D:\something in your user directory (tried it)

Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class Files.

Consider both solutions using the getProperty static method of System class.

String os = System.getProperty("os.name"); if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0 ) // Unix File folder = new File("/home/tmp"); else if(os.indexOf("win") >= 0) // Windows File folder = new File("D:\\temp"); else throw Exception("your message"); 

On Unix-like systems no logical discs. You can try create on /tmp or /home Below code for create temp dirrectory in your home directory:

String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("user.home"):"D:\\"; System.out.println(myPathCandidate); //Check write permissions File folder = new File(myPathCandidate); if (folder.exists() && folder.isDirectory() && folder.canWrite()) < System.out.println("Create directory here"); >else

or, for /tmp — system temp dicecrory. Majority of users can write here:

String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("java.io.tmpdir"):"D:\\"; 

Since Java 7, you can use the Files utility class, with the new Path class. Note that exception handling has been omitted in the examples below.

// uses os separator for path/to/folder. Path file = Paths.get("path","to","file"); // this creates directories in case they don't exist Files.createDirectories(file.getParent()); if (!Files.exists(file)) < Files.createFile(file); >StreamResult result = new StreamResult(file.toFile()); transformer.transform(source, result); 

this covers the generic case, create a folder if it doesn’t exist and a file on that folder.

In case you actually want to create a temporary file, as written in your example, then you just need to do the following:

// this create a temporary file on the system's default temp folder. Path tempFile = Files.createTempFile("xxx", "xml"); StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE)); transformer.transform(source, result); 

Note that with this method, the file name will not correspond exactly to the prefix you used ( xxx , in this case).

Still, given that it’s a temp file, that shouldn’t matter at all. The DELETE_ON_CLOSE guarantees that the file will get deleted when closed.

Источник

Using Java nio to create a subdirectory and file

My directory structure is starts from the current application directory, Means in current projects directory which looks like following. I know how to create directory but I need to create sub directory I tried with following code what should be next steps ? Then you can use , see example below: Or, using your code as is, you can use: Solution 2: You can create directory and file in one code line: will not throw an exception if the folder already exists and returns Path in any case.

Using Java nio to create a subdirectory and file

I’m creating a simple program that will try to read in «conf/conf.xml» from disk, but if this file or dir doesn’t exist will instead create them.

I can do this using the following code:

 // create subdirectory path Path confDir = Paths.get("./conf"); // create file-in-subdirectory path Path confFile = Paths.get("./conf/conf.xml"); // if the sub-directory doesn't exist then create it if (Files.notExists(confDir)) < try < Files.createDirectory(confDir); >catch (Exception e ) < e.printStackTrace(); >> // if the file doesn't exist then create it if (Files.notExists(confFile)) < try < Files.createFile(confFile); >catch (Exception e ) < e.printStackTrace(); >> 

My questions is if this really the most elegant way to do this? It seems superflous to need to create two Paths simple to create a new file in a new subdirectory.

You could declare your confFile as File instead of Path . Then you can use confFile.getParentFile().mkdirs(); , see example below:

// . File confFile = new File("./conf/conf.xml"); confFile.getParentFile().mkdirs(); // . 

Or, using your code as is, you can use:

Files.createDirectories(confFile.getParent()); 

You can create directory and file in one code line:

Files.createDirectories(confDir) will not throw an exception if the folder already exists and returns Path in any case.

You could do the following:

// Get your Path from the string Path confFile = Paths.get("./conf/conf.xml"); // Get the portion of path that represtents directory structure. Path subpath = confFile.subpath(0, confFile.getNameCount() - 1); // Create all directories recursively /** * Creates a directory by creating all nonexistent parent directories first. * Unlike the method, an exception * is not thrown if the directory could not be created because it already * exists. * */ Files.createDirectories(subpath.toAbsolutePath())) 

Unable to create directory in LINUX (java.nio.file, Unable to create directory in LINUX (java.nio.file.AccessDeniedException) Ask Question Asked 1 year, 9 months ago. Modified 1 year, 1 month ago. Viewed 1k times -1 I’m trying to make a job to automate the process of creating a folder. I can make the job work on windows …

How to create a directory in Java?

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

With Java 7, you can use Files.createDirectories() .

Files.createDirectories(Paths.get("/path/to/directory")); 

You can try FileUtils#forceMkdir

FileUtils.forceMkdir("/path/directory"); 

This library have a lot of useful functions.

Directory — How to create a folder in Java?, Browse other questions tagged java directory create-directory or ask your own question. The Overflow Blog A conversation with Stack Overflow’s new CTO, Jody Bailey (Ep. 461)

How to create a directory and sub directory structure with java?

Hello there I want to create the directories and sub directories with the java. My directory structure is starts from the current application directory, Means in current projects directory which looks like following.

Images | |+ Background | |+ Foreground | |+Necklace |+Earrings |+Etc. 

I know how to create directory but I need to create sub directory I tried with following code what should be next steps ?

File file = new File("Images"); file.mkdir(); 

You can use file.mkdir() or File.mkdirs() to create a directory. Between the two, the latter method is more tolerant and will create all intermediate directories as needed. Also, since I see that you use «\\» in your question, I would suggest using File.separator for a portable path separator string.

Starting from Java 7 , you can use the java.nio.file.Files & java.nio.file.Paths classes.

Path path = Paths.get("C:\\Images\\Background\\..\\Foreground\\Necklace\\..\\Earrings\\..\\Etc"); try < Files.createDirectories(path); >catch (IOException e)

This is a tricky solution (because I used only one path to go to the whole structure).

If you don’t like tricky solutions, you can use 4 simple paths instead:

Path p1 = Paths.get("C:\\Images\\Background"); Path p2 = Paths.get("C:\\Images\\Foreground\\Necklace"); Path p3 = Paths.get("C:\\Images\\Foreground\\Earrings"); Path p4 = Paths.get("C:\\Images\\Foreground\\Etc"); 

and then call the createDirectories method for all of them:

Files.createDirectories(p1); Files.createDirectories(p2); Files.createDirectories(p3); Files.createDirectories(p4); 

You can create all parent directories by using File.mkdirs().

File.mkdirs() — Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

You could do it with File#mkdirs() and something like,

// The "/" is cross-platform safe as a path-separator in Java. // So is "\\" but that's twice the characters! String path = createImages.getAbsolutePath() + "/Images"; File f = new File(path); if (!f.isDirectory()) < boolean success = f.mkdirs(); if (success) < System.out.println("Created path: " + f.getPath()); >else < System.out.println("Could not create path: " + f.getPath()); >> else

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

Create Directory in Java, Use the mkdir () Function to Create Directories in Java. First, the instance of the file class is created. Then the parameter is passed to this instance, which is the directory path we want to make. Finally, the mkdir () method is invoked using the file object, creating the required directory. For example,

How to create a folder in Java?

How can I create an empty folder in Java?

File f = new File("C:\\TEST"); try < if(f.mkdir()) < System.out.println("Directory Created"); >else < System.out.println("Directory is not created"); >> catch(Exception e)

Call File.mkdir , like this:

With Java 7 and newer you can use the static Files.createDirectory() method of the java.nio.file.Files class along with Paths.get .

Files.createDirectory(Paths.get("/path/to/folder")); 

The method Files.createDirectories() also creates parent directories if these do not exist.

new File('/path/to/folder').mkdir(); 

Creating files using java.nio.file Functionality, The easiest way to create a Path Object is to use the java.nio.files.Paths factory class. The class has a static get ()method which can be used to obtain a reference to a file or directory. The method accepts either a string, or a sequence of strings (which it will join to form a path) as parameters.

Источник

Оцените статью