Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

How to create file in Java Example

In this example we are going to see how to create a new file in Java. It’s fairly easy to do so, using Java File class.

First of all, you have to format a string that describes the file path in your file system that you want to create this file into. For this example, I’ve worked on a Windows system, I have a testFolder in my Desktop and I want to create a new text file in it called newFile.txt. So the file path for that will be: "F:\nikos7\Desktop\testFiles\newFile.txt" (of course, the accepted Java format of the ‘\’ character is ‘\\). If I was working in a UNIX system, the file path would be something like this : /home/nikos/Desktop/testFolder/newFile.txt/.

So you notice that the separator is different depending on the operating system. To solve this, File class has a special field named separator that contains the platform dependent separator, for you to format correct file paths.

So this is how you can create a new file:

1. Using File class

CreateFileExample.java:

package com.javacodegeeks.core.io;

import java.io.File;
import java.io.IOException;

public class CreateFileExample {
	
	private static final String FILE_PATH="F:\\nikos7\\Desktop\\testFiles\\newFile.txt";

	public static void main(String[] args) {
		
		// This does not actually create a file
		File file = new File(FILE_PATH);
		
		try {
			//create a new file if it doesn't exist already
			file.createNewFile();
	
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

The important thing to notice here is that File file = new File(FILE_PATH) does not actually create the file in the file system. file.createNewFile() actually creates and empty file, only if that file does not already exist.

You might think that File file = new File(FILE_PATH) actually creates a file, because most of the times you use it in conjunction with an InputStream or an OutputStream. That’s because when you open an OutputStream to a file, you then actually create it.

2. Using I/O streams

Here is how you can create the file using a FileOutputStream.

CreateFileExample.java:

package com.javacodegeeks.core.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class CreateFileExample {
	
	private static final String FILE_PATH="F:\\nikos7\\Desktop\\testFiles\\newFile.txt";

	public static void main(String[] args) {
		
		// This does not actually create a file
		File file = new File(FILE_PATH);
		
		OutputStream stream = null;
		
		try {
			
			stream = new FileOutputStream(FILE_PATH);
		
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

FileInputStream doesn’t actually create a file, it expects to read an already created file.

3. Using RandomAccessFile

RandomAccessFile is a very handy class that helps with file manipulation in Java, and is actually one of the most recommended classes when it come to File interaction.

CreateFileExample.java:

package com.javacodegeeks.core.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class CreateFileExample {
	
	private static final String FILE_PATH="F:\\nikos7\\Desktop\\testFiles\\newFile.txt";

	public static void main(String[] args) {
		
		// This does not actually create a file
		File file = new File(FILE_PATH);
		
		RandomAccessFile randomAccessFile =null;
		
		try {
			
			randomAccessFile = new RandomAccessFile(file,"rw");
		
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				randomAccessFile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Ok, in this case you actually create the file and you also, open it with a mode. That is the “rw”, which means that you create and open the file that you actually want to read and write into. You could use “r” or “w” to read or write only.

4. Using NIO

Of course NIO offers the necessary API to create a new File.

CreateFileExample.java:

package com.javacodegeeks.core.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateFileExample {
	
	private static final String FILE_PATH="F:\\nikos7\\Desktop\\testFiles\\newFile.txt";

	public static void main(String[] args) {
						
		try {
			Path path = Files.createFile(Paths.get(FILE_PATH));
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

5. Create a file and set POSIX permissions

Using NIO, you can do something a bit more complicated and very very handy: You can set the POSIX permissions (of course your system has to comply with POSIX) you want in a String like syntax.

CreateFileExample.java:

package com.javacodegeeks.core.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

public class CreateFileExample {
	
	private static final String FILE_PATH="home/nikos/Desktop/testFolder/newFile.txt";

	public static void main(String[] args) {
			
		Set perms = PosixFilePermissions.fromString("rw-r--r--");
		
		FileAttribute<Set> fileAttrs = PosixFilePermissions.asFileAttribute(perms);
		
		try {
			
			Path path = Files.createFile(Paths.get(FILE_PATH),fileAttrs);
		
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Download Source Code

This was an example on how to create a file in Java. You can download the source code of this example : CreateFileExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close