Creating files in java examples

Java File Class

The File class of the java.io package is used to perform various operations on files and directories.

There is another package named java.nio that can be used to work with files. However, in this tutorial, we will focus on the java.io package.

File and Directory

A file is a named location that can be used to store related information. For example,

main.java is a Java file that contains information about the Java program.

A directory is a collection of files and subdirectories. A directory inside a directory is known as subdirectory.

Create a Java File Object

To create an object of File , we need to import the java.io.File package first. Once we import the package, here is how we can create objects of file.

// creates an object of File using the path File file = new File(String pathName); 

Here, we have created a file object named file . The object can be used to work with files and directories.

Читайте также:  Python list to csv string

Note: In Java, creating a file object does not mean creating a file. Instead, a file object is an abstract representation of the file or directory pathname (specified in the parenthesis).

Java File Operation Methods

Operation Method Package
To create file createNewFile() java.io.File
To read file read() java.io.FileReader
To write file write() java.io.FileWriter
To delete file delete() java.io.File

Java create files

To create a new file, we can use the createNewFile() method. It returns

  • true if a new file is created.
  • false if the file already exists in the specified location.

Example: Create a new File

// importing the File class import java.io.File; class Main < public static void main(String[] args) < // create a file object for the current location File file = new File("newFile.txt"); try < // trying to create a file based on the object boolean value = file.createNewFile(); if (value) < System.out.println("The new file is created."); >else < System.out.println("The file already exists."); >> catch(Exception e) < e.getStackTrace(); >> > 

In the above example, we have created a file object named file . The file object is linked with the specified file path.

File file = new File("newFile.txt"); 

Here, we have used the file object to create the new file with the specified path.

If newFile.txt doesn’t exist in the current location, the file is created and this message is shown.

However, if newFile.txt already exists, we will see this message.

Java read files

To read data from the file, we can use subclasses of either InputStream or Reader.

Example: Read a file using FileReader

Suppose we have a file named input.txt with the following content.

This is a line of text inside the file. 

Now let’s try to read the file using Java FileReader .

// importing the FileReader class import java.io.FileReader; class Main < public static void main(String[] args) < char[] array = new char[100]; try < // Creates a reader using the FileReader FileReader input = new FileReader("input.txt"); // Reads characters input.read(array); System.out.println("Data in the file:"); System.out.println(array); // Closes the reader input.close(); >catch(Exception e) < e.getStackTrace(); >> > 
Data in the file: This is a line of text inside the file. 

In the above example, we have used created an object of FileReader named input. It is now linked with the input.txt file.

FileReader input = new FileReader("input.txt"); 

To read the data from the input.txt file, we have used the read() method of FileReader .

Java write to files

To write data to the file, we can use subclasses of either OutputStream or Writer.

Example: Write to file using FileWriter

// importing the FileWriter class import java.io.FileWriter; class Main < public static void main(String args[]) < String data = "This is the data in the output file"; try < // Creates a Writer using FileWriter FileWriter output = new FileWriter("output.txt"); // Writes string to the file output.write(data); System.out.println("Data is written to the file."); // Closes the writer output.close(); >catch (Exception e) < e.getStackTrace(); >> > 
Data is written to the file. 

In the above example, we have created a writer using the FileWriter class. The writer is linked with the output.txt file.

FileWriter output = new FileWriter("output.txt"); 

To write data to the file, we have used the write() method .

Here when we run the program, the output.txt file is filled with the following content.

This is the data in the output file. 

Java delete files

We can use the delete() method of the File class to delete the specified file or directory. It returns

Note: We can only delete empty directories.

Example: Delete a file

import java.io.File; class Main < public static void main(String[] args) < // creates a file object File file = new File("file.txt"); // deletes the file boolean value = file.delete(); if(value) < System.out.println("The File is deleted."); >else < System.out.println("The File is not deleted."); >> > 

In the above example, we have created an object of File named file. The file now holds the information about the specified file.

File file = new File("file.txt"); 

Here we have used the delete() method to delete the file specified by the object.

Table of Contents

Источник

Java Create and Write To Files

To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try. catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):

Example

import java.io.File; // Import the File class import java.io.IOException; // Import the IOException class to handle errors public class CreateFile < public static void main(String[] args) < try < File myObj = new File("filename.txt"); if (myObj.createNewFile()) < System.out.println("File created: " + myObj.getName()); >else < System.out.println("File already exists."); >> catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> > 

To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the » \ » character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt

Example

File myObj = new File("C:\\Users\\MyName\\filename.txt"); 

Write To a File

In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:

Example

import java.io.FileWriter; // Import the FileWriter class import java.io.IOException; // Import the IOException class to handle errors public class WriteToFile < public static void main(String[] args) < try < FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); >catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> > 

To read the file above, go to the Java Read Files chapter.

Источник

Java Create File Examples

Last updated: 27 June 2019 Creating files in Java is easy. In this post, we’ll look at four different ways to create files in Java. All we need to do is import the relevant package and use relevant methods. The examples below make use of java.io.file , java.io.fileOutputStream , and java.nio package. These classes are provided out of the box in Java API. We also look at creating a file with Apache Commons.

Create File with java.io.file class

In the first example, we will use createNewFile() method from the java.io.file class. This method returns a boolean value. It returns false if the file already exists, or true if created.

import java.io.File; import java.io.IOException; public class CreateFileJavaExamples < public static void main(String[] args) < File file = new File("c://examples//newFile.txt"); try < if (file.createNewFile()) < System.out.println("File create"); >else < System.out.println("File already exists!"); >> catch (IOException e) < System.out.println(e.getMessage()); >> > 

Using java.io.fileOutputStream

The next example uses fileOutputStream . It’s important to note that this is mostly used to create a file and write content to it in one go.

import java.io.FileOutputStream; public class CreateFileJavaExamples < public static void main(String[] args) < try < new FileOutputStream("newFile.txt", true); >catch (Exception e) < System.out.println(e.getMessage()); >> > 

If the file doesn’t exist, the above method will create it. If the file exists, passing true will just append content to it.

NOTE: Be careful when using fileOutputStream . If the file exists with content, if we pass false as the parameter to the fileOutputStream method, it will overwrite the file and the content will be lost!

Create File with java.nio Package

In the following example, we will use java.nio package which was introduced in JDK 7.

In order to create a file with the nio package, we first need to set the path and then use the createFile() method from Files class. Creating files via the new nio package is the preferred option as the API is more intuitive.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateFileJavaExamples < public static void main(String[] args) < try < Path newFilePath = Paths.get("src/test/resources/newFile.txt"); Files.createFile(newFilePath); >catch (IOException e) < >> > 

The above code example assumes the path src/test/resources already exists.

Apache Commons FileUtils

If you don’t want to use standard libraries provided out of the box from Java, you can use FileUtils class from Apache Commons

import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class CreateFileJavaExamples < public static void main(String[] args) < File myFile = new File("src/test/resources/newFile.txt"); try < FileUtils.touch(myFile); >catch (IOException e) < System.out.println(e.getMessage()); >> > 

In the above example, we use the touch method to create a file.

Источник

Creating file in Java

In Java create file tutorial, we show how to create a file in Java. We create files with built-in classes including File , FileOutputStream , and Files . We also use two third-party libraries: Apache Commons IO and Google Guava.

A is a computer resource for recording data discretely in a computer storage device.

The tutorials shows five ways to create a file in Java. The examples create empty files.

Java creating file with File

The File’s createNewFile method creates a new, empty file named by the pathname if a file with this name does not yet exist.

package com.zetcode; import java.io.File; import java.io.IOException; public class JavaCreateFileEx < public static void main(String[] args) throws IOException < File file = new File("src/main/resources/myfile.txt"); if (file.createNewFile()) < System.out.println("File has been created."); >else < System.out.println("File already exists."); >> >

The createNewFile returns true if the named file does not exist and was successfully created; false if the named file already exists.

Java creating file with FileOutputStream

In the second example, we create a new, empty file with FileOutputStream .

package com.zetcode; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class JavaCreateFileEx2 < public static void main(String[] args) throws FileNotFoundException, IOException < FileOutputStream fout = null; try < fout = new FileOutputStream("src/main/resources/myfile.txt"); >finally < if (fout != null) < fout.close(); >> > >

The file is created when FileOutputStream object is instantiated. If the file already exists, it is overridden.

FileNotFoundException is thrown if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.

Java creating file with Files

Java 7 introduced Files , which consists exclusively of static methods that operate on files, directories, or other types of files. Its createFile method creates a new and empty file, failing if the file already exists.

package com.zetcode; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class JavaCreateFileEx3 < public static void main(String[] args) throws IOException < Path path = Paths.get("src/main/resources/myfile.txt"); try < Files.createFile(path); >catch (FileAlreadyExistsException ex) < System.err.println("File already exists"); >> >

The example creates a new, empty file with Files .

Path path = Paths.get("src/main/resources/myfile.txt");

A Path object is created. It is used to locate a file in a file system.

The new file is created with Files.createFile .

> catch (FileAlreadyExistsException ex) 

FileAlreadyExistsException is thrown if the file already exists.

Java creating file with Apache Commons IO

The next example creates a file with Apache Commons IO library.

For the project we need the commons-io dependency.

package com.zetcode; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class JavaCreateFileEx4 < public static void main(String[] args) throws IOException < FileUtils.touch(new File("src/main/resources/myfile.txt")); >>

The new file is created with FileUtils.touch method.

Java creating file with Google Guava

In the following example, we create a new file with Google Guava library.

 com.google.guava guava 23.4-jre  

For the project we need the guava dependency.

package com.zetcode; import com.google.common.io.Files; import java.io.File; import java.io.IOException; public class JavaCreateFileEx5 < public static void main(String[] args) throws IOException < Files.touch(new File("src/main/resources/myfile.txt")); >>

The new file is created with Files.touch . It accepts a File as a parameter.

In this article we have shown several ways how to create a file in Java. We have used built-in tools and third-party libraries.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Оцените статью