Create new file in folder java

Creating a New File in Java

Learn to create a new file using different techniques including NIO Path, IO File, OutputStream, and open-source libraries such as Guava and Apache commons.

1. Create New File using Java NIO

The Files.createFile(path, attribs) is the best way to create a new, empty and writable file in Java and it should be your preferred approach in the future if you are not already using it.

  • The createFile() method takes the Path interface instead of the File. It checks if the file already exists, and creates the file thereafter.
  • Checking any existing file and creating the file is done in a single atomic operation.
  • The attribs an optional list of file attributes to set atomically when creating the file.
  • It returns FileAlreadyExistsException If a file of that name already exists.
  • It returns IOException if an I/O error occurs or the parent directory does not exist.

Example 1: Create a new writable file

String TEXT_FILE = "C:/temp/io/textFile.txt"; Path textFilePath = Paths.get(TEXT_FILE); Files.createFile(textFilePath);

Example 2: Create a new read-only file

Set the file attributes while creating the file. In the given example, we are setting read-only (“ r “) access for the owner, group, and others using the string “r–r–r–“.

String TEXT_FILE = "C:/temp/io/textFile.txt"; Set permissions = PosixFilePermissions .fromString("r--r--r--"); FileAttribute attribs = PosixFilePermissions .asFileAttribute(permissions); Path textFilePath = Paths.get(TEXT_FILE); Files.createFile(textFilePath, attribs); 

2. Using File.createNewFile()

Use File.createNewFile() method to create a new file if and only if a file with this name does not yet exist. Checking any existing file and creating the file is an atomic operation.

This method returns a boolean value –

  • true if the file is created successfully.
  • false if the file already exists.
  • IOException If an I/O error occurred.
String TEXT_FILE = "C:/temp/io/textFile.txt"; File textFile = new File(TEXT_FILE); boolean isFileCreated = textFile.createNewFile(); 

The constructor automatically creates a new file in the given location. Note that if a file with a given name already exists, it will be overwritten.

It throws FileNotFoundException if the given file path represents a directory, or a new file cannot be created for any reason.

String TEXT_FILE = "C:/temp/io/textFile.txt"; try(FileOutputStream fos = new FileOutputStream(TEXT_FILE))< // We can write data as byte[] // fos.write(data, 0, data.length); >

To include Guava, add the following to pom.xml.

 com.google.guava guava 31.1-jre 

The Files.touch() method is similar to the Unix touch command. It creates an empty file or updates the last updated timestamp

The touch command, when used without any option, creates an empty file assuming the file doesn’t exist. If the file exists it changes the timestamp.

String TEXT_FILE = "C:/temp/io/textFile.txt"; com.google.common.io.Files.touch(new File(TEXT_FILE));

5. Apache Commons IO’s FileUtils

To include Apache Commons IO, add the following to pom.xml.

The FileUtils.touch() is very similar to the previous example. It also implements the same behavior as the “touch” utility on Unix.

Also, as from v1.3 this method creates parent directories if they do not exist. It throws an IOException if the last modified date of the file cannot be set.

String TEXT_FILE = "C:/temp/io/textFile.txt"; org.apache.commons.io.FileUtils.touch(new File(TEXT_FILE));

Источник

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.

Источник

Читайте также:  Line break element html
Оцените статью