Archives: File Handling

Java – Change File Date / Time using Commons FileUtils

[code lang=”java”]import java.io.IOException;
import org.apache.commons.io.FileUtils;

import java.io.File;

public class Main {

public static void main(String[] args) {
try {
File file = new File("pic.jpg");
long lastModified1 = file.lastModified();
FileUtils.touch(file);
long lastModified2 = file.lastModified();
System.out.println("File date / time was updated: " + (lastModified2 > lastModified1));
} catch (IOException ex) {
ex.printStackTrace();
}
}

}[/code]

Output:

File date / time was updated: true


Java – Calculate Directory Size using Commons FileUtils

[code lang=”java”]import java.io.File;
import org.apache.commons.io.FileUtils;

public class DirectorySizeSample {

public static void main(String[] args) {

// Using FileUtils.sizeOfDirectory() we can calculate
// the size of a directory including it sub directory
long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));

System.out.println("Size: " + size + " bytes");

}
}[/code]


Java – Set File Permission Example

[code lang=”java”][/code]
import java.io.File;
import java.io.IOException;

public class FilePermissionExample
{
public static void main( String[] args )
{
try {

File file = new File(“/mydir/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();
}
}
}
[code][/code]