Create file java mkdirs

Java File

The Java File class, java.io.File in the Java IO API gives you access to the underlying file system. Using the Java File class you can:

This Java File tutorial will tell you more about how.

Note: The Java File class only gives you access to the file and directory meta data. If you need to read or write the content of files, you should do so using either FileInputStream, FileOutputStream or RandomAccessFile.

Note: If you are want to Java NIO (Java’s non-blocking IO API) you will have to use the java.nio.FileChannel class instead. Both Java File and FileChannel works, but in case you want a pure Java NIO solution use the Java NIO FileChannel class.

Create a File

Before you can do anything with the file system or File class, you must create a Java File instance. Here is an example of creating a Java File instance:

File file = new File("c:\\data\\input-file.txt");

The Java File constructor takes as parameter the file path in the underlying file system of the file you want the File instance to point to. Note, that the file or directory path does not actually have to reference an existing file or directory. If it doesn’t, you won’t get an exception from the File constructor. This behaviour is useful when we want to check if a file exists, or we want to create a new file.

Читайте также:  Вводи пароль

The Java File class also has a few other constructors you can use to instantiate File instances in different ways.

Check if File or Directory Exists

You can check if a file referenced by a Java File object exists using the File exists() method. Here is an example of checking if a file exists:

File file = new File("c:\\data\\input-file.txt"); boolean fileExists = file.exists();

The above code also works for directories. The only change you need to make to check if a directory exists is to pass a file system path to a directory to the Java File constructor, intead of a path to a file. Here is an example of checking if a directory exists:

File file = new File("c:\\data"); boolean fileExists = file.exists();

Create a Directory if it Does Not Exist

You can use the Java File class to create directories if they don’t already exists. The File class contains the method mkdir() and mkdirs() for that purpose.

The mkdir() method creates a single directory if it does not already exist. Here is an example of creating a single directory via the Java File class:

File file = new File("c:\\users\\jakobjenkov\\newdir"); boolean dirCreated = file.mkdir();

Provided that the directory c:\users\jakobjenkov already exists, the above code will create a subdirectory of jakobjenkov named newdir . The mkdir() returns true if the directory was created, and false if not.

The mkdirs() will create all directories that are missing in the path the File object represents. Here is an example of creating multiple directories via the Java File class:

File file = new File("c:\\users\\jakobjenkov\\newdir"); boolean dirCreated = file.mkdirs();

Provided that the C drive exists, this example will create all the directories in the path c:\users\jakobjenkov\newdir . The mkdirs() method will return true if all the directories were created, and false if not.

File Length

The Java File class enables you to read the length in bytes of a file. To read the length of a file, call the File length() method. Here is an example of reading the length of a file via the Java File length() method:

File file = new File("c:\\data\\input-file.txt"); long length = file.length();

Rename or Move File or Directory

To rename (or move) a file, call the method renameTo() on the File class. Here is a simple example:

File file = new File("c:\\data\\input-file.txt"); boolean success = file.renameTo(new File("c:\\data\\new-file.txt"));

As briefly mentioned earlier, the renameTo() method can also be used to move a file to a different directory. The new file name passed to the renameTo() method does not have to be in the same directory as the file was already residing in.

The renameTo() method returns boolean (true or false), indicating whether the renaming was successful. Renaming of moving a file may fail for various reasons, like the file being open, wrong file permissions etc.

The Java File renameTo() method also works for directories, by the way. Just pass a path to a directory to the File constructor, instead of a path to a file.

Delete File or Directory

To delete a file call the Java File delete() method. Here is a simple example:

File file = new File("c:\\data\\input-file.txt"); boolean success = file.delete();

The delete() method returns boolean (true or false), indicating whether the deletion was successful. Deleting a file may fail for various reasons, like the file being open, wrong file permissions etc.

The Java File delete() method also works for directories, meaning you can also delete directories with it.

Delete Directory and Subdirectories Recursively

The Java File delete() method can only delete a directory if the directory is empty. To delete a directory that contains files and subdirectories you must iterate through the directory and delete all files and subdirectories first, before you can delete the root directory. This iteration has to be carried out recursively, so you also delete all content of subdirectories and their subdirectories. Otherwise the deletion of the root directory will fail. Here is a Java method that can delete a directory and all its subdirectories and their files recursively:

public static boolean deleteDir(File dir) < File[] files = dir.listFiles(); if(files != null)< for(File file : files)< if(file.isDirectory())< deleteDir(file); >else < file.delete(); >> > return dir.delete(); >

Check if Path is File or Directory

As mentioned several times earlier in this Java File tutorial, a File object can point to both a file or a directory. You can check if a File object points to a file or directory, by calling its isDirectory() method. This method returns true if the File points to a directory, and false if the File points to a file. Here is a simple example:

File file = new File("c:\\data"); boolean isDirectory = file.isDirectory();

Read List of Files in Directory

You can obtain a list of all the files in a directory by calling either the Java File list() method or the listFiles() method. The list() method returns an array of String’s with the file and / or directory names of directory the File object points to. The listFiles() returns an array of File objects representing the files and / or directories in the directory the File points to.

Here is an example of listing all files in a directory via the Java File list() and listFiles() methods:

File file = new File("c:\\data"); String[] fileNames = file.list(); File[] files = file.listFiles();

Источник

Class File

The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property file.separator , and is made available in the public static fields separator and separatorChar of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.

A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir , and is typically the directory in which the Java virtual machine was invoked.

The parent of an abstract pathname may be obtained by invoking the getParent() method of this class and consists of the pathname’s prefix and each name in the pathname’s name sequence except for the last. Each directory’s absolute pathname is an ancestor of any File object with an absolute abstract pathname which begins with the directory’s absolute pathname. For example, the directory denoted by the abstract pathname «/usr» is an ancestor of the directory denoted by the pathname «/usr/local/bin» .

  • For UNIX platforms, the prefix of an absolute pathname is always «/» . Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix «/» and an empty name sequence.
  • For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by «:» and possibly followed by «\\» if the pathname is absolute. The prefix of a UNC pathname is «\\\\» ; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.

Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.

A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object’s owner, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.

Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

Interoperability with java.nio.file package

The java.nio.file package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the java.io.File class. The toPath method may be used to obtain a Path that uses the abstract path represented by a File object to locate a file. The resulting Path may be used with the Files class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.

Источник

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