Introduces different ways to create files in Java.
- Created using File
- Created using Path and Files
- Created using the Commons-io library
Let`s see with an example.
Create a file using the File class
You can create a file using File.createNewFile()
. Returns a boolean indicating whether the file was created.
try {
File file = new File("/home/js/test/text.txt");
boolean success = file.createNewFile();
if (!success) {
System.out.println("Failed to create a file : /home/js/test/text.txt");
}
} catch (IOException e) {
e.printStackTrace();
}
If the file already exists, the file creation fails and false is returned.
Create using Path and Files (Java7)
You can create a file using the Path and Files of the Java7 nio package.
The following example creates a file.
try {
Path filePath = Paths.get("/home/js/test/text.txt");
Files.createFile(filePath);
} catch (IOException e) {
e.printStackTrace();
}
If there is a directory that does not exist in the file path, an exception is raised and the file creation fails.
For example, when the code below is executed, if the folder /home/js/test/new_dir/
does not exist, an exception is thrown and the file cannot be created.
try {
Path filePath = Paths.get("/home/js/test/new_dir/text.txt");
Files.createFile(filePath);
} catch (IOException e) {
e.printStackTrace();
}
When I run the code, the following exception is thrown.
java.nio.file.NoSuchFileException: /home/js/test/new_dir/text.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.createFile(Files.java:632)
at example.io.CreateFile.main(CreateFile.java:37)
So, in this case, you need to create the folder first and create the file.
Create file using Commons-io library
The Commons-io library provides the FileUtils class, with which you can create files.
Gradle project adds the following to dependencies of build.gradle
.
dependencies {
compile group: 'commons-io', name: 'commons-io', version: '2.6'
...
}
For projects that use other build systems such as Maven, refer to mvnrepository.com and configure it.
FileUtils.touch()
creates the file passed as an argument.
try {
File file = new File("/home/js/test/new_dir/text.txt");
FileUtils.touch(file);
} catch (IOException e) {
e.printStackTrace();
}
Unlike the Files class above, FileUtils.touch()
creates a folder and creates a file if there is an uncreated folder in the file path.
So, even if /home/js/test/new_dir
does not exist, it will not affect the creation of the file.
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)