Showing posts with label directory. Show all posts
Showing posts with label directory. Show all posts

Tuesday, 10 May 2011

Rename the File or Directory in java

This example shows function, which renames the file or directory. The function takes old name and new name, and renames accordingly.

public boolean renameFile(String oldName, String newName)
{
File oldfile = new File(oldName);
if(!oldfile.exists())
{
System.out.println("File or directory does not exist.");
return false;
}
File newfile = new File(newName);
boolean reName = oldfile.renameTo(newfile);
if(!reName )
{
System.out.println("File or directory does not rename successfully.");
return reName ;
}else{
System.out.println("File or directory rename is successfully.");
return reName;
}
}

Monday, 18 April 2011

How to display all the directories in a directory?

This function displays directories in a directory using filter.
public static void displayAllDir(String dirName) {
File dir = new File(dirName); //eg. C:
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("Either dir does not exist
or is not a directory");
}
else {
for (int i=0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}

How to display all the files in a directory ?

This function takes directory name and prints all files in it:

public static void displayAllDir(String dirName) {
File dir = new File(dirName); //eg. C:
String[] children = dir.list();
if (children == null) {
System.out.println( "Either dir does not exist or is
not a directory");
}
else {
for (int i=0; i< children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}

Displaying root directories in the system using java

This can be done using static method File.listRoots().

Eg.
File[] roots = File.listRoots();
System.out.println("Root directories :");
for (int i=0; i < roots.length; i++) {
System.out.println(roots[i].toString());
}

Finding the current working directory in java

The current directory can be found using getProperty() method.

String curDir = System.getProperty("user.dir");

How to traverse a directory in java?

This can be done by getting list of all children and then traversing further deep. See following function :

public static void traverseDirectory(File dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
traverseDirectory
(new File(dir, children[i]));
}
}
}

How to get the size of a directory in java?

This can be done with the help of FileUtils.sizeofDirectory(File Name) method of FileUtils class. This gives size in bytes.

import java.io.File;
import org.apache.commons.io.FileUtils;

public class GetDirSize {
public static void main(String[] args) {
long size = FileUtils.sizeOfDirectory
(new File("C:/Windows/Fonts"));
System.out.println("Size: " + size + " bytes");
}
}


How to search all files inside a directory using java?

This can be done using dir.list() method of File class.

File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist or
is not a directory");
}
else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}

How to get the parent directory of a file in java?

Use file.getParent() method for this:

File file = new File("C:/File/demo.txt");
String strParentDirectory = file.getParent();

How to get the last modification time of a directory in java?

This can be done through file.lastModified() method of File class.

import java.io.File;
import java.util.Date;

public class DirTest {
public static void main(String[] args) {
File file = new File("C://FileIO//demo.txt");
System.out.println("last modifed:" +
new Date(file.lastModified()));
}
}



Printing the directory hierarchy in java

Following example shows how to print the hierarchy of a specified directory using file.getName() and file.listFiles() method of File class.

import java.io.File;
import java.io.IOException;

public class FileUtil {
public static void main(String[] a)throws IOException{
showDir(1, new File("d:\\Java"));
}
static void showDir(int indent, File file)
throws IOException {
for (int i = 0; i < indent; i++)
System.out.print('-');
System.out.println(file.getName());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
showDir(indent + 4, files[i]);
}
}
}

Example will print output of following form(try to see in the form of packages like java.io.File, java.lang etc):
-Java
-----io
---------File.txt
---------BufferReader.txt
-----lang

How to check whether a directory is empty or not?

Following example gets the size of a directory by using file.isDirectory(),file.list() and file.getPath() methodsof File class.

File file = new File("/data");
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
System.out.println("The " + file.getPath() +
" is not empty!");

How to delete a directory in java?

Following example demonstares how to delete a directory after deleting its files and directories by the use ofdir.isDirectory(),dir.list() and deleteDir() methods of File class.

import java.io.File;

public class Main {
public static void main(String[] argv) throws Exception {
deleteDir(new File("c:\\temp"));
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir
(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
System.out.println("The directory is deleted.");
}
}

How to create directories recursively ?

This can be done through mkdirs() function in File class.

import java.io.File;

public class Main {
public static void main(String[] args) {
String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";
File file = new File(directories);
boolean result = file.mkdirs();
System.out.println("Status = " + result);
}
}

Friday, 15 April 2011

Files-Directory listing in Java

This example lists the files and subdirectories in a directory.
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i &amp;amp;amp;lt; children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}

// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);

// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();

// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);

Traversing the Files and Directories Under a Directory
This example implements methods that recursively visits all files and directories under a directory.
// Process all files and directories under dir
public static void visitAllDirsAndFiles(File dir) {
process(dir);

if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}

// Process only directories under dir
public static void visitAllDirs(File dir) {
if (dir.isDirectory()) {
process(dir);

String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllDirs(new File(dir, children[i]));
}
}
}

// Process only files under dir
public static void visitAllFiles(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllFiles(new File(dir, children[i]));
}
} else {
process(dir);
}
}