IO File
Create File
java.io.File class is used to create new file. When create file object of File class and pass the file name in their constructor and object call this method createNewFile() method then file is created succesfully it returns true or else return false. This method only create File we can not write into the file. And if method is not created then its throws java.io.IOException
Relative path
When we give just file name then its create the file in the project root directory
Absolute Path
When we give the location of where it shoud be created in our system then we use this. While creating the path we should use file.seperator property of system so that make our program platform independent.
Example:
package com.IOFile;
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) throws IOException {
String fileSeparator = System.getProperty("file.separator");
System.out.println(fileSeparator);
//absolute file name with path
String absoluteFilePath = fileSeparator+"home"+fileSeparator+"codersarts"+fileSeparator+"file.txt";
File file = new File(absoluteFilePath);
if(file.createNewFile()) {
System.out.println(absoluteFilePath+" File Created");
} else
System.out.println("File "+absoluteFilePath+" already exists");
//file name only
file = new File("file.txt");
if(file.createNewFile()) {
System.out.println("file.txt File Created in Project root directory");
}else
System.out.println("File file.txt already exists in the project root directory");
//relative path
String relativePath = "tempFiles"+fileSeparator+"file2.txt";
file = new File(relativePath);
if(file.createNewFile()) {
System.out.println(relativePath+" File Created in Project root directory");
}else
System.out.println("File "+relativePath+" already exists in the project root directory");
}
}
Output
/home/codersarts/file.txt File Created
file.txt File Created in Project root directory
tempFiles/file2.txt File Created in Project root directory
Create File wih java.io.FileOutputStream class
If you want to write content in the file when creating file then you can use this class. FileOutputStream.write(byte[] b) method.
Example:
package com.IOFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateFileOutputStream {
public static void main(String[] args) throws IOException {
String data = "Hello Coders arts ";
FileOutputStream fos = new FileOutputStream("file3.txt");
fos.write(data.getBytes());
fos.flush();
fos.close();
}
}
Output
Hello Coders arts
Java NIO Files.write()
If you want to write content in the file when creating file then you can use java NIO Files class and its a good option because we don’t need to worry to close IO resources.
Example:
package com.IOFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CreateFileOutputStream {
public static void main(String[] args) throws IOException {
String data = "Hello Coders arts ";
Files.write(Paths.get("file4.txt"), data.getBytes());
}
}
Output
Hello Coders arts
DeleteFiles
delete() method is use to delete the files/folder which is empty. This method returns true if file deleted or else return false if file is not exist.
To delete non-empty files/folder you can use Files.walkFileTree().
Example:
package com.IOFile;
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
//absolute file name with path
File file = new File("/home/codersarts/file.txt");
if(file.delete()) {
System.out.println("/home/codersarts/file.txt File deleted");
} else
System.out.println("File /home/codersarts/file.txt doesn't exist");
//file name only
file = new File("file3.txt");
if(file.delete()) {
System.out.println("file.txt File deleted from Project root directory");
} else
System.out.println("File file.txt doesn't exist in the project root directory");
//relative path
file = new File("tempFiles/file2.txt");
if(file.delete()) {
System.out.println("tempFiles/file2.txt File deleted from Project root directory");
} else
System.out.println("File tempfiles/file2.txt doesn't exist in the project root directory");
//delete empty directory
file = new File("tempFiles");
if(file.delete()) {
System.out.println("tempFiles directory deleted from Project root directory");
} else
System.out.println("tempFiles directory doesn't exist or not empty in the project root directory");
//try to delete directory with files
file = new File("/home/codersarts/temp");
if(file.delete()) {
System.out.println("/home/codersarts/temp directory deleted from the given location");
} else
System.out.println("/home/codersarts/temp directory doesn't exist or not empty in the given location");
}
}
Output
File /home/codersarts/file.txt doesn't exist
File file.txt doesn't exist in the project root directory
File tempfiles/file2.txt doesn't exist in the project root directory
tempFiles directory doesn't exist or not empty in the project root directory
/home/codersarts/temp directory doesn't exist or not empty in the given location
File Seperators in Java : java.io.File
Class contains 4 static separator variables. all of these are final variables and system dependent.
- File.separator: Platform dependent default name-separator character as String. For windows, it’s ‘\’ and for unix it’s ‘/’.
- File.separatorChar: Similar as separator but it’s char.
- File.pathSeparator: Platform dependent variable for path-separator. For example PATH or CLASSPATH variable list of paths separated by ‘:’ in Unix systems and ‘;’ in Windows system.
- File.pathSeparatorChar: Similar as pathSeparator but it’s char.
Example:
package com.IOFile;
import java.io.File;
public class FilesSeperator {
public static void main(String[] args) {
System.out.println("File.separator in Unix = "+File.separator);
System.out.println("File.separatorChar in Unix = "+File.separatorChar);
System.out.println("File.pathSeparator in Unix = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar in Unix = "+File.pathSeparatorChar);
}
}
Output
File.separator in Unix = /
File.separatorChar in Unix = /
File.pathSeparator in Unix = :
File.pathSeparatorChar in Unix
Move File
If you want to move the file from location to another then you can use renameTo() method . If file is already available in the destination then it fails to move the file then return fasle or else return true.
Rename File
renameTo() method is also use to reanme the filename . If file succesfully rename then it return true or else false.
Example:
package com.IOFile;
import java.io.File;
public class RenameOrMoveFile {
public static void main(String[] args) {
//absolute path rename file
File file = new File("/home/codersarts/coder.txt");
File newFile = new File("/home/codersarts/coders.txt");
if(file.renameTo(newFile)) {
System.out.println("File rename success");
}else {
System.out.println("File rename failed");
}
//relative path rename file
file = new File("applications.properties");
newFile = new File("application.properties");
if(file.renameTo(newFile)) {
System.out.println("File rename success");;
}
else {
System.out.println("File rename failed");
}
//java move file from one directory to another
file = new File("/home/codersarts/coders.txt");
newFile = new File("application.properties");
if(file.renameTo(newFile)) {
System.out.println("File move success");;
}
else {
System.out.println("File move failed");
}
//when source file is not present
file = new File("/home/codersarts/art.txt");
newFile = new File("art.txt");
if(file.renameTo(newFile)) {
System.out.println("File move success");;
}
else {
System.out.println("File move failed");
}
// when destination already have a file with same name
file = new File("/home/codersarts/arts.txt");
newFile = new File("/home/codersarts/arts.txt");
if(file.renameTo(newFile)) {
System.out.println("File move success");;
}
else {
System.out.println("File move failed");
}
}
}
Output
File rename success
File rename success
File move success
File move failed
File move failed
FileSize
We can get the size of file by using 3 classes File Class, FileChannel Class andFileUtils class.
Get Size of file by Using File Class: length() method of file class return the file lengtth in bytes before using this method try to ensure that this not a directory becuase for directory it returns unspecified value.
Example:
package com.IOFile;
import java.io.File;
public class GetFileSizeUsingFile {
static final String FILE_NAME = "/home/codersarts/Pictures/1.png";
public static void main(String[] args) {
File file = new File(FILE_NAME);
if (!file.exists() || !file.isFile()) return;
System.out.println(getFileSizeBytes(file));
System.out.println(getFileSizeKiloBytes(file));
System.out.println(getFileSizeMegaBytes(file));
}
private static String getFileSizeBytes(File file) {
return file.length() + " bytes";
}
private static String getFileSizeKiloBytes(File file) {
return (double) file.length() / 1024 + " kb";
}
private static String getFileSizeMegaBytes(File file) {
return (double) file.length() / (1024 * 1024) + " mb";
}
}
Output
198374 bytes
193.724609375 kb
0.18918418884277344 mb
Get Size of file by Using FileChannel Class: This class has method size() which is use to calculate the file size.
Example:
package com.IOFile;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GetFileSizeUsingFileChannel {
static final String FILE_NAME = "/home/codersarts/Pictures/1.png";
public static void main(String[] args) {
Path filePath = Paths.get(FILE_NAME);
FileChannel fileChannel;
try {
fileChannel = FileChannel.open(filePath);
long fileSize = fileChannel.size();
System.out.println(fileSize / 1024 + " kb");
fileChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
193 kb
Get Size of file by Using Apache commons IO FileUtils Class
Example:
package com.IOFile;
import java.io.File;
public class GetFileSizeUsingFileUtils {
static final String FILE_NAME = "/home/codersarts/Pictures/1.png";
public static void main(String[] args) {
File file = new File(FILE_NAME);
long fileSize = FileUtils.sizeOf(file);
System.out.println(fileSize /1024 + " kb");
}
}
This program can used when you are using ApachecommonsIO in your Project.
GetFileExtension
getFileExtension method is used to get the extension of File but this method is not belong to the File Class.
Example:
package com.IOFile;
import java.io.File;
public class GetFileExtension {
public static void main(String[] args) {
File file = new File("/home/codersarts/arts.txt");
System.out.println("File extension is: "+getFileExtension(file));
//file name without extension
file = new File("/home/codersarts/arts");
System.out.println("File extension is: "+getFileExtension(file));
//file name with dot
file = new File("/home/codersarts/small.bin.gz.db");
System.out.println("File extension is: "+getFileExtension(file));
//hidden files without extension
file = new File("/home/codersarts/.htaccess");
System.out.println("File extension is: "+getFileExtension(file));
}
private static String getFileExtension(File file) {
String fileName = file.getName();
if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
return fileName.substring(fileName.lastIndexOf(".")+1);
else return "";
}
}
Output
File extension is: txt
File extension is:
File extension is: db
File extension is:
Check file exists or Not
exist() method in java.io.File use to check whether file is exist or not in the given location.
Example:
Hello Coders artpackage com.IOFile;
import java.io.File;
import java.io.IOException;
public class CheckFileExist {
public static void main(String[] args) {
File file = new File("/home/codersarts/output.txt");
File notExist = new File("abc.txt");
try {
System.out.println(file.getCanonicalPath() + " exists? "+file.exists());
System.out.println(notExist.getCanonicalPath() + " exists? "+notExist.exists());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
/home/codersarts/output.txt exists? true
/home/codersarts/eclipse-workspace/IOFile/abc.txt exists? False
Check Its File or Directory
There are two method in java.io.File class isFile() , isDirectory() method which is use to check file and directory.
Example:
import java.io.File;
public class CheckFileOrDirectory {
public static void main(String[] args) {
File file = new File("/home/coders/output.txt");
File dir = new File("/home/coders");
File notExists = new File("/home/coders/output1.txt");
System.out.println("/home/coders/output.txt is file?"+file.isFile());
System.out.println("/home/coders/output.txt is directory?"+file.isDirectory());
System.out.println("/home/coders is file?"+dir.isFile());
System.out.println("/home/coders is directory?"+dir.isDirectory());
System.out.println("/home/coders/output.txt is file?"+notExists.isFile());
System.out.println("/home/coders/output.txt is directory?"+notExists.isDirectory());
}
}
Output
/home/coders/output.txt is file?false
/home/coders/output.txt is directory?false
/home/coders is file?false
/home/coders is directory?false
/home/coders/output.txt is file?false
/home/coders/output.txt is directory?false
File Last Modified date
Whenever we need to get when file is updated last in java then we can use lastModified() method of java.io.File class.
Example:
package com.IOFile;
import java.io.File;
import java.util.Date;
public class FileLastModified {
public static void main(String[] args) {
File file = new File("/home/codersarts/output.txt");
long timestamp = file.lastModified();
System.out.println("output.txt last modified date = "+new Date(timestamp));
}
}
Output
output.txt last modified date = Mon Nov 18 17:51:27 IST 2019
File Permisssion
File class has method to check the file permission for application user. It contains other method to set file permission for user and everyone.
Example:
import java.io.File;
public class FilePermission {
public static void main(String[] args) {
File file = new File("/home/codersarts/output.txt");
//check file permissions for application user
System.out.println("File is readable? "+file.canRead());
System.out.println("File is writable? "+file.canWrite());
System.out.println("File is executable? "+file.canExecute());
//change file permissions for application user only
file.setReadable(false);
file.setWritable(false);
file.setExecutable(false);
//change file permissions for other users also
file.setReadable(true, false);
file.setWritable(true, false);
file.setExecutable(true, true);
}
}
Output
File is readable? true
File is writable? true
File is executable? False
getPath(),AbsolutePath(),canonicalPath() methods of File Class
These method is use to determine the path of any file.
getPath()
It returns the string object which contains the path of the given file object.
Example:
package com.IOFile;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class FilePath {
private static void printFilePaths(File file) throws IOException {
System.out.println("Path: " + file.getPath());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("Canonical Path: " + file.getCanonicalPath());
}
public static void main(String[] args) throws IOException, URISyntaxException {
File file = new File("/home/codersarts/output.txt");
printFilePaths(file);
// relative path
file = new File("application.properties");
printFilePaths(file);
// complex relative paths
file = new File("/home/codersarts/../codersarts/output.txt");
printFilePaths(file);
// URI paths
file = new File(new URI("file:/home/codersarts/output.txt"));
printFilePaths(file);
}
}
Output
Path: /home/codersarts/output.txt
Absolute Path: /home/codersarts/output.txt
Canonical Path: /home/codersarts/output.txt
Path: application.properties
Absolute Path: /home/codersarts/eclipse-workspace/IOFile/application.properties
Canonical Path: /home/codersarts/eclipse-workspace/IOFile/application.properties
Path: /home/codersarts/../codersarts/output.txt
Absolute Path: /home/codersarts/../codersarts/output.txt
Canonical Path: /home/codersarts/output.txt
Path: /home/codersarts/output.txt
Absolute Path: /home/codersarts/output.txt
Canonical Path: /home/codersarts/output.txt
FileName Filter
whenever you want to know that list of file in a directory of a given extension like .txt, .doc etc so We have to implement method boolean accept(File dir, String name) which is inside the FileNameFilter interface and tested for every file in the list when we call the File class listFiles() method on a particular Path.b>
Example:
package com.IOFile;
import java.io.File;
import java.io.FilenameFilter;
public class FileNameFilter {
public static void main(String[] args) {
String dir = "/home/codersarts";
String extension = ".txt";
findFiles(dir, extension);
}
private static void findFiles(String dir, String extension) {
File file = new File(dir);
if (!file.exists())
System.out.println(dir + " Directory doesn't exists");
File[] listOfFiles = file.listFiles(new FileNameFilters(extension));
if (listOfFiles.length == 0) {
System.out.println(dir + "doesn't have any file with extension " + extension);
}
else {
for (File f: listOfFiles)
System.out.println("File: " + dir + File.separator + f.getName());
}
}
// FileNameFilter implementation
public static class FileNameFilters implements FilenameFilter {
private String extension;
public FileNameFilters(String extension) {
this.extension = extension.toLowerCase();
}
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(extension);
}
}
}
Output
File: /home/codersarts/output.txt
Alternate Solution for This problem using lambda Expression : Then there is no need to provide implementation for FileNameFilter.
Example:
package com.IOFile;
import java.io.File;
import java.io.FilenameFilter;
public class FileNameFilter {
public static void main(String[] args) {
String dir = "/home/codersarts";
String extension = ".txt";
findFiles(dir, extension);
}
private static void findFiles(String dir, String extension) {
File file = new File(dir);
if (!file.exists())
System.out.println(dir + " Directory doesn't exists");
File[] listOfFiles = file.listFiles((d, s) -> {
return s.toLowerCase().endsWith(extension);
});
if (listOfFiles.length == 0) {
System.out.println(dir + "doesn't have any file with extension " + extension);
}
else {
for (File f: listOfFiles)
System.out.println("File: " + dir + File.separator + f.getName());
}
}
}
Output
File: /home/codersarts/output.txt