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

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books