Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How to Create a File in Java? – File Handling Concepts

Last updated on Oct 01,2019 7.2K Views

29 / 72 Blog from Java Core Concepts

File handling in Java is necessary to perform various tasks on a file, such as create, read, write, etc. In this article, I will tell you how to create a file in Java using various methods.

Below topics are covered in this tutorial:

Let’s begin.

What is Java?

Java is one of the most popular programming languages used to create Web applications and platforms, Also it is class-based, object-oriented language similar to C++, but with advanced features. Java is platform-independent because the Java compiler converts the source code to bytecode. It was designed for allowing developers to write the code that would run on any machine.

One of the biggest reasons why Java is so popular is its platform independence. Java is still a relevant programming language that shows no sign of declining in popularity and that’s why it’s worth learning. Most of the developers pick it up as their first programming language because it’s easy to learn.

Now let’s move further and understand the execution flow of a Java program.

Execution flow of a Java Program

The below figure shows involved in executing a Java program:

Java program execution - Create a file in java - Edureka

All high level (also called third-generation) programming languages allow you to write the programs in a language similar(although much simpler) than natural language. The high-level program is called the source code.

Step1: Write the source code. A compiler is a computer program that translates computer code written in the source language into the target language. 

Step2: Compile translates source code into machine code.

Step3: As soon as a Java program is compiled, the next step is to generate a Java bytecode. We can also say that Java bytecode is the machine code in the form of a .class file. Hence, Java bytecode is the result of the compilation of a Java program, an intermediate representation of the program which is machine-independent.

Step4: In order to execute Java code you need to convert it into a  machine language. For this, we need a compiler and interpreter. An interpreter translates program one statement at a time. Whereas, a compiler scans the entire program and translates it as a whole into machine code so it gives errors after all the program gets executed whereas interpreter check line by line code and gives you the errors.

Step5: In the last step the compiler bytecode translates the entire code into machine code.

Now that you know the basics fundamentals of Java, let’s move further and understand what is a file in Java.

What is File in Java?

File is nothing but a simple storage of data, in Java language. A file system may implement restrictions to certain operations, such as reading, writing, and executing. These restrictions are  known as access permissions. While reading a file in Java, we must know Java file class. Java File class represents the files and directory pathnames in an abstract manner. The File class has several methods for working with directories and files such as creating new directories or files, deleting and renaming directories or files,etc. The File object represents the actual file/directory on the disc.

 Now let’s understand the various methods to create a file in Java.

Methods to Create File in Java

1. Create File with java.io.File Class

To create a new file, you need to use  File.createNewFile() method. This method returns a boolean value:

  • true if the file is accomplished.

  • false if the file already exists or the operation neglects to open for some reason.

This method also throws java.io.IOException when it’s not able to create the file. 

When we create the File object by passing the file name, it can be with an absolute path, or we can only provide the file name or we can provide the relative path. For a non-absolute path, File object tries to locate files in the project root directory. If we run the program from the command line, for the non-absolute path, File object tries to locate files from the current directory. Instances of the File class are unchangeable; that is, once created, the abstract pathname represented by a File object will never change.

Now, let’s take a small example and understand how it works.

File file = new File("c://temp//testFile1.txt");
//create the file.
if (file.createNewFile()){
System.out.println("File is created!");
}
else{
System.out.println("File already exists.");
}
//write content
FileWriter writer = new FileWriter (file);
writer.write("Test data");
writer.close();

Kindly note that this method will only create a file, but not write any content to it. Now let’s move further and understand the next method.

2. Create File with java.io.FileOutputStream Class

If you want to create a new file and at the same time if you want to write some data into it, you can use a FileOutputStream write method.  In Java, FileOutputStream is a byte stream class. To write the data to file, you have to convert the data into bytes and then save it to the file.

For Example:

String data = "Test data";
FileOutputStream out = new FileOutputStream("c://temp//testFile2.txt");
out.write(data.getBytes());
<span>out.close();

FileOutputStream class stores the data in the form of individual bytes. It can be used to create text files. A file represents the storage of data on a second storage media like hard disk or CD. FileOutputStream.write() method automatically create a new file and write content to it.

3. Create File with Java.nio.file.Files – Java NIO

Files.write() is the best way to create the file and it should be your preferred approach in future if you are not already using it. This is a good option because we don’t have to worry about closing IO resources. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform’s line separator

Method:

public static Path createFile(Path path, FileAttribute<?>... attrs) throws IOException

Creates a new and empty file, and this fails if the file already exists.

Parameters:

path – The path to create a file.

attrs – an optional list of file attributes to set atomically when creating the file.

For Example:

String data = "Test data";
Files.write(Paths.get("c://temp//testFile3.txt");
data.getBytes());
//or
List<String> lines = Arrays.asList("1st line", "2nd line");
Files.write(Paths.get("file6.txt");
lines,
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);

This is how you need to create it. Next, let’s see temporary file creation.

4. Java Can Also Create Temporary File

Creating a temporary file in java can be required in many scenarios, but mostly it will happen during unit tests where you don’t want to store the results. As soon as test case is finished, you do not care about file content.

Creating a temporary file using java.io.File.createTempFile()

Public class TemporaryFileExample{
Public static void main(string[] args){
try{
final path path = Files.createTempFile("myTempFile",".txt");

System.out.println("Temp file : " + path);
// delete file on exist.
path.toFile().deleteonExit();
} catch (IOException e){
e.printStackTrace();
}
}
}

Creating a temporary file using NIO

Public class TemporaryFileExample{
Public static void main(string[] args){
File temp;
try{
temp = File.createTempFile("myTempFile" , ".txt");

System.out.println("Temp file created : " +
temp.getAbsolutePath());
} catch (IOException e){
e.printStackTrace();
}
}
}

To create a temporary file, the following two methods are used.

1. createTempFile(Path, String, String, FileAttribute<?>… attrs) – Creates a tmp file in the specified directory.

The above method accepts four arguments.

Path – > to specify the directory in which the file to be created.

String -> to mention prefix of the filename. Use null to avoid prefix.

String -> to mention suffix of the file name. i.e. file extension. Use null to use .tmp as an extension.

attrs -> This is optional to mention a list of file attributes to set atomically when creating the file

Eg. Files.createTempFile(path,null, null); – creates a temp file with .tmp extension in the specified path

2. createTempFile(String, String, FileAttribute<?>) – Creates temp file in the default temporary directory of the system/server.

Eg: Files.createTempFile(null,null) – creates a temp file in the default temp folder of the system. In windows, temp folder may be C:UsersusernameAppDataLocalTemp , where username is your windows login id 

Hence, Java can create new files, and that’s how it works. With this, we come to an end of this article on How to Create a File in Java. I hope you found it informative. If you wish to learn more, you can check out our other Java Blogs as well.

Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.

Got a question for us? Please mention it in the comments section of this “How to Create a File in Java” article and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Create a File in Java? – File Handling Concepts

edureka.co