Java creating directory and file

Java, create a file and a folder

The first time it is run (on many machines) the directory does not exist. After the first time, then directory will have been created.

«c:/»+Utilities.timeFormat(); 1-a) Put files in a sub-directory of user.home 1-b) User home is a reliable path on Mac. & *nix, as well as Windows. 2) Don’t use String objects to represent a File . 3) Form paths using valid separators with the new File(parentFile, «thefilename») constructor.

5 Answers 5

You have to use File.mkdir() or File.mkdirs() method to create a folder.

 String path="c:/newDirectory"; File file=new File(path); if(!file.exists()) file.mkdirs(); // or file.mkdir() file=new File(path + "/" + Utilities.timeFormat()); if(file.createNewFile())

Thanks for this information. What it seems that I might need to do is: 1) IF(folder does not exist) 2) Place new file in folder.

without knowing your actual code which is creating the directory:

use mkdirs() instead of mkdir()

Can you check that you have permissions to create a folder in c:/ ?

Can you show us the stacktrace too?

If «newDirectory» doesn’t exist yet, you should use the method mkdirs() from the File class to create all the directories in between.

The fact that the directory doesn’t exist is probably why it isn’t working he first time through. As many have pointed out use mkdirs() will ensure if the file you want to write is in subfolders it will create them. Now here is what it might look like:

File file = new File( new File("c:/newDirectory"), Utilities.timeFormat() ); if( !file.getParentFile().exists() ) < file.getParentFile().mkdirs(); >OutputStream stream = new BufferedOutputStream( new FileOutputStream( file ) ); try < // put your code here to write the file >finally

Notice I’m not using + to create a path. Instead I create a File object, and pass it the parent File and the name of the file. Also notice I’m not putting path separators in between the parent and filename. Using the File constructor takes care of a system independent way of creating paths.

Источник

Creating and Reading Directories

Some of the methods previously discussed, such as delete , work on files, links and directories. But how do you list all the directories at the top of a file system? How do you list the contents of a directory or create a directory?

This section covers the following functionality specific to directories:

Listing a File System’s Root Directories

You can list all the root directories for a file system by using the FileSystem.getRootDirectories method. This method returns an Iterable , which enables you to use the enhanced for statement to iterate over all the root directories.

The following code snippet prints the root directories for the default file system:

Iterable dirs = FileSystems.getDefault().getRootDirectories(); for (Path name: dirs)

Creating a Directory

You can create a new directory by using the createDirectory(Path, FileAttribute) method. If you don’t specify any FileAttributes , the new directory will have default attributes. For example:

Path dir = . ; Files.createDirectory(path);

The following code snippet creates a new directory on a POSIX file system that has specific permissions:

Set perms = PosixFilePermissions.fromString("rwxr-x---"); FileAttribute attr = PosixFilePermissions.asFileAttribute(perms); Files.createDirectory(file, attr);

To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method, createDirectories(Path, FileAttribute) . As with the createDirectory(Path, FileAttribute) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:

Files.createDirectories(Paths.get("foo/bar/test"));

The directories are created, as needed, from the top down. In the foo/bar/test example, if the foo directory does not exist, it is created. Next, the bar directory is created, if needed, and, finally, the test directory is created.

It is possible for this method to fail after creating some, but not all, of the parent directories.

Creating a Temporary Directory

You can create a temporary directory using one of createTempDirectory methods:

The first method allows the code to specify a location for the temporary directory and the second method creates a new directory in the default temporary-file directory.

Listing a Directory’s Contents

You can list all the contents of a directory by using the newDirectoryStream(Path) method. This method returns an object that implements the DirectoryStream interface. The class that implements the DirectoryStream interface also implements Iterable , so you can iterate through the directory stream, reading all of the objects. This approach scales well to very large directories.

Remember: The returned DirectoryStream is a stream. If you are not using a try- with-resources statement, don’t forget to close the stream in the finally block. The try- with-resources statement takes care of this for you.

The following code snippet shows how to print the contents of a directory:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir)) < for (Path file: stream) < System.out.println(file.getFileName()); >> catch (IOException | DirectoryIteratorException x) < // IOException can never be thrown by the iteration. // In this snippet, it can only be thrown by newDirectoryStream. System.err.println(x); >

The Path objects returned by the iterator are the names of the entries resolved against the directory. So, if you are listing the contents of the /tmp directory, the entries are returned with the form /tmp/a , /tmp/b , and so on.

This method returns the entire contents of a directory: files, links, subdirectories, and hidden files. If you want to be more selective about the contents that are retrieved, you can use one of the other newDirectoryStream methods, as described later in this page.

Note that if there is an exception during directory iteration then DirectoryIteratorException is thrown with the IOException as the cause. Iterator methods cannot throw exception exceptions.

Filtering a Directory Listing By Using Globbing

If you want to fetch only files and subdirectories where each name matches a particular pattern, you can do so by using the newDirectoryStream(Path, String) method, which provides a built-in glob filter. If you are not familiar with glob syntax, see What Is a Glob?

For example, the following code snippet lists files relating to Java: .class, .java, and .jar files.:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.")) < for (Path entry: stream) < System.out.println(entry.getFileName()); >> catch (IOException x) < // IOException can never be thrown by the iteration. // In this snippet, it can // only be thrown by newDirectoryStream. System.err.println(x); >

Writing Your Own Directory Filter

Perhaps you want to filter the contents of a directory based on some condition other than pattern matching. You can create your own filter by implementing the DirectoryStream.Filter interface. This interface consists of one method, accept , which determines whether a file fulfills the search requirement.

For example, the following code snippet implements a filter that retrieves only directories:

DirectoryStream.Filter filter = newDirectoryStream.Filter() < public boolean accept(Path file) throws IOException < try < return (Files.isDirectory(path)); >catch (IOException x) < // Failed to determine if it's a directory. System.err.println(x); return false; >> >;

Once the filter has been created, it can be invoked by using the newDirectoryStream(Path, DirectoryStream.Filter) method. The following code snippet uses the isDirectory filter to print only the directory’s subdirectories to standard output:

Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir, filter)) < for (Path entry: stream) < System.out.println(entry.getFileName()); >> catch (IOException x)

This method is used to filter a single directory only. However, if you want to find all the subdirectories in a file tree, you would use the mechanism for Walking the File Tree.

Источник

How to create a file in a directory in java?

Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn’t get created in the right directory.

13 Answers 13

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

Using new File(«/a/b/test.txt») works for both systems. On Windows, it will be written to the same disk as where JVM runs.

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

On Windows, both \\ and / are valid. The createNewFile() is by the way unnecessary when you write to it with FileOutputStream anyway.

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

A better and simpler way to do that :

File f = new File("C:/a/b/test.txt"); if(!f.exists())

Surprisingly, many of the answers don’t give complete working code. Here it is:

public static void createFile(String fullPath) throws IOException < File file = new File(fullPath); file.getParentFile().mkdirs(); file.createNewFile(); >public static void main(String [] args) throws Exception < String path = "C:/donkey/bray.txt"; createFile(path); >

Create New File in Specified Path

import java.io.File; import java.io.IOException; public class CreateNewFile < public static void main(String[] args) < try < File file = new File("d:/sampleFile.txt"); if(file.createNewFile()) System.out.println("File creation successfull"); else System.out.println("Error while creating File, file already exists in specified path"); >catch(IOException io) < io.printStackTrace(); >> > 

Program Output:

File creation successfull

To create a file and write some string there:

BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file")); bufferedWriter.write("Some string"); // to write some data // bufferedWriter.write(""); // for empty file bufferedWriter.close(); 

This works for Mac and PC.

For using the FileOutputStream try this :

When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.

 String absolutePath = . try< File file = new File(absolutePath); file.mkdirs() ; //all parent folders are created //now the file will be created when you start writing to it via FileOutputStream. >catch (Exception e)

I was here tackling this same problem and I finally solved it.

The goal is to create a file (example a .txt file) within a folder.

File f = new File("C:/a/b/test.txt"); 
//get the file's absolute path. You could input it yourself // but I think it is better to have a function to handle // system rules on how to format the path string String myFolder = "b"; String myFile = "test.txt"; String folderPath = myFolder.getAbsolutePath(); //will get the entire path for you String pathToFile = folderPath + File.separator + myFile; // this will probably throw a exception, you want to make sure you handle it try < File newFile = new File(pathToFile); if (newFile.createNewFile()) < System.out.println("bwahahah success"); >else < System.out.println("file creation failed"); >>catch(IOException e) < System.out.println(e.getMessage()); // you will need to print the message in order to get some insight on what the problem is. >// you can also add a throw if within the if statement with other checks in order to know where the error is coming from, but to keep it short this is the gist of it. // Really hope this will assist anyone that stumbles upon this same issue. 

Other resources for further reading: everything on java paths & files

Please comment if there is anything I might also overlook, lemme absorb some of that knowledge

Just joining some answers together.

import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; class Scratch < public static void main(String[] args) < String fileTargetLocation = "C:\\testing\\"; String fileNameAndExtension = "test.txt"; boolean fileCreated = createFile(fileTargetLocation, fileNameAndExtension); if (fileCreated) < String stringForFile = "This is some test text to write into the file."; writeIntoFile(fileTargetLocation, fileNameAndExtension, stringForFile); >> /** * Attempts to create a file at the given location, with the given file name and desired extension. * * @param fullPath full path to folder in which the file needs to be created, example: C:\testing\ * (ending with a foreword slash) * @param fileNameAndExtension file name and desired extension. Example: environment.properties, test.txt * @return successful file creation boolean */ public static boolean createFile(String fullPath, String fileNameAndExtension) < try < return new File(fullPath + fileNameAndExtension).createNewFile(); >catch (IOException io) < io.printStackTrace(); >return false; > /** * Attempt to write into the given file. * * @param fullPath full path to folder in which the file needs to be created, example: C:\testing\ * (ending with a foreword slash) * @param fileNameAndExtension file name and extension. Example: environment.properties, test.txt * @param whatToWriteToFile string to write to the file */ public static void writeIntoFile(String fullPath, String fileNameAndExtension, String whatToWriteToFile) < try (BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(fullPath + fileNameAndExtension))) < bufferedWriter.write(whatToWriteToFile); >catch (IOException io) < io.printStackTrace(); >> > 

Источник

Читайте также:  Операторы регулярных выражений python
Оцените статью