Example of Files in java.nio.file API | Java NIO 2

By Arvind Rai, November 28, 2013
java.nio.file.Files has been introduced in JDK 7. Files deals with directory and files. It can create and delete directory as well as files. It also creates link between the existing files and link directory. Files contain static methods to perform the task. Here we will give the examples of some important methods of Files.

Example of Files.newBufferedReader in java.nio.file API

java.nio.file.Files provides static methods that reads and writes the files and directories. Files.newBufferedReader opens the text files to read. newBufferedReader() method returns BufferedReader that reads the file. The method signature is
newBufferedReader(Path p, Charset ch)
 
The Path provides file path and Charset provides the information in which character set data is to read. newBufferedReader reads data form byte stream to characters. In our example we are reading a text file using StandardCharsets.UTF_8.

NewBufferedReaderExample.java
package com.concretepage.io.file;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class NewBufferedReaderExample {
	public static void main(String[] args) throws IOException {
	    //Get the instance of Path
	    Path path = Paths.get("c:/temp","test.txt");
	    //opens the file to read
	    BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
	    String s = null;
	    while((s=reader.readLine())!=null){
	    	System.out.println(s);	
	    }
	}
}
 
In the example, we have created Path by Paths.get. Files.newBufferedReader needs the arguments of Path and StandardCharsets. StandardCharsets defines the char set encoding. Finally we are printing the file in the console.

Example of Files.copy in java.nio.file API

Files.copy copies the data form one file to another file. Files.copy has different constructors that accept different type of parameters. Files.copy accepts Path as source and OutputStream as destination. Files.copy also accepts parameter InputStream as source file and Path as destination file and it also accepts Path as source and destination file both with java.nio.file.StandardCopyOption. Find the example.

CopyExample.java
package com.concretepage.io.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class CopyExample {
	public static void main(String[] args) throws IOException {
		
	    //Get the instance of Path of Source File
	    Path pathSource = Paths.get("c:/cp","test.txt");
		
	    // Using Path and OutputStream with Files.copy 
	    //get the File to be written
	    File destFile = new File("c:/temp/newTest1.txt");
	    FileOutputStream fos = new FileOutputStream(destFile);
		
	    //copy a file to destination file and returns no of bytes written
	    long noOfBytes = Files.copy(pathSource, fos);
	    System.out.println(noOfBytes);
	    
	    //Using InputStream and Path with Files.copy 
	    File sourceFile = new File("c:/cp/test.txt");
	    FileInputStream fis = new FileInputStream(sourceFile);
	    Path destPath1 = Paths.get("c:/temp","newTest2.txt");
	    
	    noOfBytes = Files.copy(fis,destPath1,StandardCopyOption.REPLACE_EXISTING);
	    System.out.println(noOfBytes);
	    
	    //Using Path for source and destination of file with Files.copy
	    Path destPath2 = Paths.get("c:/temp","newTest3.txt");
	    Path target = Files.copy(pathSource,destPath2,StandardCopyOption.REPLACE_EXISTING);
	    System.out.println(target.getFileName());
	}
}
 
In the example, we have shown all the three overloading method of Files.copy.
1. copy(Path source, OutputStream out)
We are passing Path instance and OutputStream and here file is written from Path source file to destination file by OutputStream.
2. copy(InputStream in, Path target, CopyOption... options)
Here we are copying one file to another file by passing InputStream as source file and Path as destination file. StandardCopyOption.REPLACE_EXISTING overwrites if file already exists.
3. copy(Path source, Path target, CopyOption... options)
Here source and destination both are as Path instance.

Create Directory and Temp Directory Using java.nio.file.Files

java.nio.file.Files has the methods that creates directory and temp directory as required. Directory can be created by passing Path arguments and FileAttribute. FileAttribute is optinal. Because posix is not permitted in Windows. Find the different methods and their usability.

Files.createDirectories() in java.nio.file.Files

createDirectories(Path dir, FileAttribute<?>... attributes) supports creating parent as well as child directories. It does not throw exception if file already exists.

Files.createDirectory() in java.nio.file.Files

Files.createDirectory(Path dir, FileAttribute<?>... attributes) only creates the last child directory and does not create parent directory. It throws exception if child already exists.

Files.createTempDirectory()in java.nio.file.Files

Files.createTempDirectory(String prefix, FileAttribute<?>... attributes) creates temp directory with given prefix in the default temp directory of File system. Files.createTempDirectory(Path dir, String prefix, FileAttribute<?>... attributes) creates the temp directory in specified Path. Find the example to create directory and temp directory using java.nio.file.Files.

CreateDirectoryExample.java
package com.concretepage.io.file;
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 CreateDirectoryExample {
	public static void main(String[] args) throws IOException {
		Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwx--x");
	      FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(perms);
	      Path path = Paths.get("D:", "Parent","Child");
	      
	      //This line of code will not work in Windows OS
	      //Files.createDirectories(path,fileAttributes);
	      
	      //creates Directory as Directory as D:\Parent\Child
	      Files.createDirectories(path);
	      
	      Path path1 = Paths.get("D:", "Parent","Child1");
	     
	      //creates Directory as Directory Child1 under  as D:\Parent 
	      Files.createDirectory(path1);
	      
	      //creates temp directory in file system temp directory
	      Files.createTempDirectory("Concretepage");
	      
	      //creates temp directory in the specified path
	      Files.createTempDirectory(path,"Concretepage");
	}
}
 

Example of Files.createFile(path) and Files.createTempFile(String prefix, String suffix)

Files.createFile creates a file in the specified Path. If file already exits, it throws exception. Files.createTempFile creates a temp file in the default directory of the file system.

CreateFileExample.java
package com.concretepage.io.file;
import java.io.File;
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.Calendar;
import java.util.Set;

public class CreateFileExample {
	public static void main(String[] args) throws IOException {
		  Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwx--x");
	      FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(perms);
	      Path path = Paths.get("d:", "cp","file.txt");
	      
	      // will not work on windows
	      //Files.createFile(path, fileAttributes);
	      
	      //creates a file
          Files.createFile(path);
	      
          //Create temp file in default location
	      File.createTempFile("concretepage", String.valueOf(Calendar.getInstance().getTime().getTime()));
	}
}
 

Example of Files.createLink(Path link, Path existing) and Files.createSymbolicLink(Path link, Path target)

Files.createLink creates a link for a file which will locate to other directory. In Files.createSymbolicLink, target Path may not exist and creates a symbolic link for the given link Path.

CreateLinkExample.java
package com.concretepage.io.file;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateLinkExample {
	public static void main(String[] args) throws IOException {
		Path existing = Paths.get("d:", "cp","file.txt");
		Path link = Paths.get("d:", "link");
		Path linkSym = Paths.get("d:", "linkSym");
		Files.createLink(link, existing);
		Files.createSymbolicLink(linkSym, existing);
	}
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us