- Java – Create a File
- 1. Overview
- 2. Setup
- 3. Using NIO Files.createFile()
- 4. Using File.createNewFile()
- 5. Using FileOutputStream
- 6. Using Guava
- 7. Using Apache Commons IO
- 8. Conclusion
- How to Create/Write a File in Java?
- How to Create a File in Java
- How to Write Data to a File using write() method in Java
- Conclusion
- About the author
- Anees Asghar
Java – Create a File
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this quick tutorial, we’re going to learn how to create a new File in Java – first using the Files and Path classes from NIO, then the Java File and FileOutputStream classes, Google Guava, and finally the Apache Commons IO library.
This article is part of the “Java – Back to Basic” series here on Baeldung.
2. Setup
In the examples, we’ll define a constant for the file name:
private final String FILE_NAME = "src/test/resources/fileToCreate.txt";
And we’ll also add a clean-up step to make sure that the file doesn’t already exist before each test, and to delete it after each test runs:
@AfterEach @BeforeEach public void cleanUpFiles()
3. Using NIO Files.createFile()
Let’s start by using the Files.createFile() method from the Java NIO package:
@Test public void givenUsingNio_whenCreatingFile_thenCorrect() throws IOException
As you can see the code is still very simple; we’re now using the new Path interface instead of the old File.
One thing to note here is that the new API makes good use of exceptions. If the file already exists, we no longer have to check a return code. Instead, we’ll get a FileAlreadyExistsException:
java.nio.file.FileAlreadyExistsException:
4. Using File.createNewFile()
Let's now look at how we can do the same using the java.io.File class:
@Test public void givenUsingFile_whenCreatingFile_thenCorrect() throws IOException
Note that the file must not exist for this operation to succeed. If the file does exist, then the createNewFile() operation will return false.
5. Using FileOutputStream
Another way to create a new file is to use the java.io.FileOutputStream:
@Test public void givenUsingFileOutputStream_whenCreatingFile_thenCorrect() throws IOException < try(FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME))< >>
In this case, a new file is created when we instantiate the FileOutputStream object. If a file with a given name already exists, it will be overwritten. If, however, the existing file is a directory or a new file cannot be created for any reason, then we'll get a FileNotFoundException.
Additionally, note we used a try-with-resources statement – to be sure that a stream is properly closed.
6. Using Guava
The Guava solution for creating a new file is a quick one-liner as well:
@Test public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException
7. Using Apache Commons IO
The Apache Commons library provides the FileUtils.touch() method which implements the same behavior as the “touch” utility in Linux.
Therefore it creates a new empty file or even a file and the full path to it in a file system:
@Test public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException
Note that this behaves slightly differently than the previous examples: if the file already exists, the operation doesn't fail, it simply doesn't do anything.
And there we have it – 4 quick ways to create a new file in Java.
8. Conclusion
In this article, we looked at different solutions for creating a file in Java. We used classes that are part of the JDK and external libraries.
The code for the examples is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you'll have results within minutes:
How to Create/Write a File in Java?
Java provides a predefined class named “File” which can be found in the java.io package. The File class assists us in working with the files as it provides a wide range of methods such as mkdir(), getName(), and many more. If we talk about file creation and writing to the file, the createNewFile(), and write() methods of the File and FileWriter classes can be used respectively.
This write-up provides a profound understanding of the following concepts:
- How to Create a File in Java
- How to Write Data to a File in Java
- Practical Implementation of createNewFile() and write() methods
How to Create a File in Java
The file class provides a createNewFile() method that makes it possible to create an empty file and if a file is created successfully then it returns true, and if the file already exists then we will get a false value.
Example
The below-given code imports two classes: File and IOException of the java.io package:
package filehandlingexample ;
import java.io.File ;
import java.io.IOException ;
public class FileCreationExample {
public static void main ( String [ ] args ) {
try {
File newFile = new File ( "C:JavaFile.txt" ) ;
if ( newFile. createNewFile ( ) ) {
System . out . println ( "File created: " + newFile. getName ( ) ) ;
} else {
System . out . println ( "File Already Exists" ) ;
}
} catch ( IOException excep ) {
System . out . println ( "Error" ) ;
excep. printStackTrace ( ) ;
}
}
}
To create a file, we utilize the object of the File class with the createNewFile() method and the getName() method is used to get the specified name of the File. Moreover, to tackle the exceptions we utilize the try, catch statements, and within the try block, we utilize the if-else statements to handle two possibilities: file created and file already exists. While the catch block will execute to throw an exception:
The above snippet authenticates that the file created successfully.
How to Write Data to a File using write() method in Java
Java provides a built-in class FileWriter that can be used to write data to any file and to do so, the FileWriter() class provides a write() method. While working with the FileWriter class we have to utilize the close() method to close the file.
Example
Let’s consider the below code snippet that writes the data to a file:
public class FileWriteExample {
public static void main ( String [ ] args ) {
try {
FileWriter fileObj = new FileWriter ( "JavaFile.txt" ) ;
fileObj. write ( "Welcome to LinuxHint" ) ;
fileObj. close ( ) ;
System . out . println ( "Data written to the file Successfully" ) ;
} catch ( IOException e ) {
System . out . println ( "Error" ) ;
e. printStackTrace ( ) ;
}
}
}
In the above code snippet, we created an object of the FileWriter class, and within the parenthesis, we specified the file name to whom we want to write the data. Next, we utilize the write() method of the same class to write the data to the file and then close the file using the close() method. Finally, we handled the exceptions in the catch block using the IOException class.
The output validates that the write() method succeeds in writing the data to a file.
Conclusion
In java, the createNewFile(), and write() methods of File and FileWriter classes can be used respectively to create a file and to write data to a specific file. Moreover, we have to utilize the close() method when working with the FileWriter class to close the File. This write-up presents a comprehensive overview of how to create a file and how to write data to a file in java.
About the author
Anees Asghar
I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.