Create a File in Java
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main( String[] args )
{
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Set File Permission in Java
import java.io.File;
import java.io.IOException;
public class FilePermissionExample
{
public static void main( String[] args )
{
try {
File file = new File("/mkyong/shellscript.sh");
if(file.exists()){
System.out.println("Is Execute allow: " +file.canExecute());
System.out.println("Is Write allow : " + file.canWrite());
System.out.println("Is Read allow : " + file.canRead());
}
file.setExecutable(false);
file.setReadable(false);
file.setWritable(false);
System.out.println("Is Execute allow : " + file.canExecute());
System.out.println("Is Write allow : " + file.canWrite());
System.out.println("Is Read allow : " + file.canRead());
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Get file path of a file in Java
import java.io.File;
import java.io.IOException;
public class AbsoluteFilePathExample
{
public static void main(String[] args)
{
try{
File temp = File.createTempFile("i-am-a-temp-file", ".tmp" );
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
String filePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("File path : " + filePath);
}catch(IOException e){
e.printStackTrace();
}
}
}
Get Free disk space in Java
import java.io.File;
public class DiskSpaceDetail
{
public static void main(String[] args)
{
File file = new File("c:");
long totalSpace = file.getTotalSpace(); //total disk space in bytes.
long usableSpace = file.getUsableSpace(); // available space in bytes.
long freeSpace = file.getFreeSpace(); //unallocated space in bytes.
System.out.println(" === Partition Detail ===");
System.out.println(" === bytes ===");
System.out.println("Total size : " + totalSpace + " bytes");
System.out.println("Space free : " + usableSpace + " bytes");
System.out.println("Space free : " + freeSpace + " bytes");
System.out.println(" === mega bytes ===");
System.out.println("Total size : " + totalSpace /1024 /1024 + " mb");
System.out.println("Space free : " + usableSpace /1024 /1024 + " mb");
System.out.println("Space free : " + freeSpace /1024 /1024 + " mb");
}
}
Check if a file Exists
import java.io.*;
public class FileChecker {
public static void main(String args[]) {
File f = new File("c:\\mkyong.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
}
}
Delete a file in Java
import java.io.File;
public class DeleteFileExample
{
public static void main(String[] args)
{
try{
File file = new File("c:\\logfile20100131.log");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Get file size in Java
import java.io.File;
public class FileSizeExample
{
public static void main(String[] args)
{
File file =new File("c:\\java_xml_logo.jpg");
if(file.exists()){
double bytes = file.length();
double kilobytes = (bytes / 1024);
double megabytes = (kilobytes / 1024);
double gigabytes = (megabytes / 1024);
double terabytes = (gigabytes / 1024);
double petabytes = (terabytes / 1024);
double exabytes = (petabytes / 1024);
double zettabytes = (exabytes / 1024);
double yottabytes = (zettabytes / 1024);
System.out.println("bytes : " + bytes);
System.out.println("kilobytes : " + kilobytes);
System.out.println("megabytes : " + megabytes);
System.out.println("gigabytes : " + gigabytes);
System.out.println("terabytes : " + terabytes);
System.out.println("petabytes : " + petabytes);
System.out.println("exabytes : " + exabytes);
System.out.println("zettabytes : " + zettabytes);
System.out.println("yottabytes : " + yottabytes);
}else{
System.out.println("File does not exists!");
}
}
}
Get the number of lines in a file
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class LineNumberReaderExample
{
public static void main(String[] args)
{
try{
File file =new File("c:\\ihave10lines.txt");
if(file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
while (lnr.readLine() != null){
linenumber++;
}
System.out.println("Total # of lines : " + linenumber);
lnr.close();
}else{
System.out.println("File does not exists!");
}
}catch(IOException e){
e.printStackTrace();
}
}
}
List files with certain extension (filter listing of files)
import java.io.File;
import java.io.FilenameFilter;
public class FileDemo {
public static void main(String[] args) {
File f = null;
File[] paths;
try{
// create new file
f = new File("c:/test");
// create new filename filter
FilenameFilter fileNameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if(name.lastIndexOf('.')>0)
{
// get last index for '.' char
int lastIndex = name.lastIndexOf('.');
// get extension
String str = name.substring(lastIndex);
// match path name extension
if(str.equals(".txt"))
{
return true;
}
}
return false;
}
};
// returns pathnames for files and directory
paths = f.listFiles(fileNameFilter);
// for each pathname in pathname array
for(File path:paths)
{
// prints file and directory paths
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
}
Rename a file in Java
import java.io.File;
public class RenameFileExample
{
public static void main(String[] args)
{
File oldfile =new File("oldfile.txt");
File newfile =new File("newfile.txt");
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
}
Copy a file in Java
Java didn’t comes with any ready make file copy function, you have to manual create the file copy process. To copy file, just convert the file into a bytes stream with FileInputStream and write the bytes into another file with FileOutputStream.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFileExample
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("Afile.txt");
File bfile =new File("Bfile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
}
Move file to a different directory
Java.io.File does not contains any ready make move file method, but you can workaround with the following two alternatives :
- File.renameTo().
- Copy to new file and delete the original file.
Rename
import java.io.File;
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Copy and Delete
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFileExample
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\folderA\\Afile.txt");
File bfile =new File("C:\\folderB\\Afile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
System.out.println("File is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
}
Get file Creation Date in Java
There are no official way to get the file creation date in Java.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class GetFileCreationDateExample
{
public static void main(String[] args)
{
try{
Process proc =
Runtime.getRuntime().exec("cmd /c dir c:\\logfile.log /tc");
BufferedReader br =
new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String data ="";
//it's quite stupid but work
for(int i=0; i<6; i++){
data = br.readLine();
}
System.out.println("Extracted value : " + data);
//split by space
StringTokenizer st = new StringTokenizer(data);
String date = st.nextToken();//Get date
String time = st.nextToken();//Get time
System.out.println("Creation Date : " + date);
System.out.println("Creation Time : " + time);
}catch(IOException e){
e.printStackTrace();
}
}
}
Get the last modified Date in Java
import java.io.File;
import java.text.SimpleDateFormat;
public class GetFileLastModifiedExample
{
public static void main(String[] args)
{
File file = new File("c:\\logfile.log");
System.out.println("Before Format : " + file.lastModified());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("After Format : " + sdf.format(file.lastModified()));
}
}
Change the last Modified Data for a file in Java
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ChangeFileLastModifiedExample
{
public static void main(String[] args)
{
try{
File file = new File("C:\\logfile.log");
//print the original last modified date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Original Last Modified Date : "
+ sdf.format(file.lastModified()));
//set this date
String newLastModified = "01/31/1998";
//need convert the above date to milliseconds in long value
Date newDate = sdf.parse(newLastModified);
file.setLastModified(newDate.getTime());
//print the latest last modified date
System.out.println("Lastest Last Modified Date : "
+ sdf.format(file.lastModified()));
}catch(ParseException e){
e.printStackTrace();
}
}
}
Make a file read only in Java
import java.io.File;
import java.io.IOException;
public class FileReadAttribute
{
public static void main(String[] args) throws IOException
{
File file = new File("c:/file.txt");
//mark this file as read only, since jdk 1.2
file.setReadOnly();
if(file.canWrite()){
System.out.println("This file is writable");
}else{
System.out.println("This file is read only");
}
//revert the operation, mark this file as writable, since jdk 1.6
file.setWritable(true);
if(file.canWrite()){
System.out.println("This file is writable");
}else{
System.out.println("This file is read only");
}
}
}
How to generate a file checksum in Java
Here is a simple example to demonstrate how to generate a file checksum value with “SHA-1” mechanism in Java.
import java.io.FileInputStream;
import java.security.MessageDigest;
public class TestCheckSum {
public static void main(String args[]) throws Exception {
String datafile = "c:\\INSTLOG.TXT";
MessageDigest md = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream(datafile);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
//convert the byte to hex format
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Digest(in hex format):: " + sb.toString());
}
}
Check if a file is hidden in Java
import java.io.File;
import java.io.IOException;
public class FileHidden
{
public static void main(String[] args) throws IOException
{
File file = new File("c:/hidden-file.txt");
if(file.isHidden()){
System.out.println("This file is hidden");
}else{
System.out.println("This file is not hidden");
}
}
}
Note
The isHidden() method is system dependent, on UNIX platform, a file is considered hidden if it’s name is begins with a “dot” symbol (‘.’); On Microsoft Windows platform, a file is considered to be hidden, if it’s marked as hidden in the file properties.
Creating a temporary file in Java
import java.io.File;
import java.io.IOException;
class TempFileDemo
{
public static void main(String[] args) throws IOException
{
System.out.println(System.getProperty("java.io.tmpdir"));
File temp = File.createTempFile("text", ".txt");
System.out.println(temp);
temp.deleteOnExit();
}
}
List all the files and folders from a directory(not recursive)
/**
* List all the files and folders from a directory
* @param directoryName to be listed
*/
public
void
listFilesAndFolders(String directoryName){
File directory =
new
File(directoryName);
File[] fList = directory.listFiles();
for
(File file : fList){
System.out.println(file.getName());
}
}
List all the files from a directory
/**
* List all the files under a directory
* @param directoryName to be listed
*/
public
void
listFiles(String directoryName){
File directory =
new
File(directoryName);
File[] fList = directory.listFiles();
for
(File file : fList){
if
(file.isFile()){
System.out.println(file.getName());
}
}
}
List all the folders from a directory (not including recursive sub folders)
/**
* List all the folder under a directory
* @param directoryName to be listed
*/
public
void
listFolders(String directoryName){
File directory =
new
File(directoryName);
File[] fList = directory.listFiles();
for
(File file : fList){
if
(file.isDirectory()){
System.out.println(file.getName());
}
}
}
List all files from a directory and sub-directories (recursive)
/**
* List all files from a directory and its subdirectories
* @param directoryName to be listed
*/
public
void
listFilesAndFilesSubDirectories(String directoryName){
File directory =
new
File(directoryName);
File[] fList = directory.listFiles();
for
(File file : fList){
if
(file.isFile()){
System.out.println(file.getAbsolutePath());
}
else
if
(file.isDirectory()){
listFilesAndFilesSubDirectories(file.getAbsolutePath());
}
}
}