Friday, October 31, 2014

Java File Object



Get parent directory as a File object

import java.io.*;
public class GetParentDirectoryAsFile
{
 public static void main(String[] args)
{
File file = new File("C://FileIO/demo.txt");
File fileParent = file.getParentFile();
System.out.println("Parent directory is : " + fileParent.getPath());
  }
}

List File system roots

import java.io.*;
public class ListFileSystemRoots
{
public static void main(String[] args)
{
File[] rootDirectories = File.listRoots();
System.out.println("Available root directories in filesystem are :  ");
for(int i=0 ; i < rootDirectories.length ; i++)
{
System.out.println(rootDirectories[i]);
    }
  }
}

List contents of a directory

import java.io.*;
public class ListContentOfDirectory
{

public static void main(String[] args)
 {
File file = new File("C://FileIO");
String[] files = file.list();
System.out.println("Listing contents of " + file.getPath());
for(int i=0 ; i < files.length ; i++)
{
System.out.println(files[i]);
    }
  }
}

Mark file or directory Read Only

import java.io.*;
public class MarkFileReadOnly
{
public static void main(String[] args)
{
File file = new File("C://FileIO//demo.txt");
boolean blnMarked  = file.setReadOnly();
System.out.println("Was file marked read only ?: " + blnMarked);
System.out.println("Is file writable ?: " + file.canWrite());
   }
}

Rename file or directory

import java.io.*;
public class RenameFileDirectory
{
public static void main(String[] args)
{
File oldName = new File("C://FileIO//source.txt");
File newName = new File("C://FileIO//destination.txt");
boolean isFileRenamed = oldName.renameTo(newName);
if(isFileRenamed)
System.out.println("File has been renamed");
else
System.out.println("Error renaming the file");
   }
}

No comments:

Post a Comment