Files and directories in java-lab 1

Here is how you use most of the File methods in day today life. The comments also tell you what to expect from  methods, especially the different ways you can get a file’s name.

File file = new File(“E:\hai123.txt”);

// does file exists

 if (file.exists()) {
 System.out.println("file exists");

// how long is the file in bytes

 System.out.println("File Bytes is" + file.length());

// get all the list of files in a directory

 File file1 = new File("E:\zip files");
 String[] fileList = file1.list();

for (String oFile : fileList) {

// check read permission for a file

 System.out.println("You " + (file.canRead() ? "have" : "hadn't") + " read permission " + file.getName());

// check write permission for a file

 System.out.println("You " + (file.canWrite() ? "have" : "hadn't") + " write permission" + file.getName());

// last modified timestamp

 System.out.println("last modified timestamp for that file " + (new Date(file.lastModified())));

// is a directory

 System.out.println("check whether the file is in a directory " + (file.isDirectory() ? "yes" : "no"));

// is this a file

 System.out.println("check the given is a file " + (file.isFile() ? "yes" : "no"));

// get a list of root drivers

 File[] fileRoots = File.listRoots();
 for (File root : fileRoots) {

// create a directory

 File filedir = new File("E:\temp");
 System.out.println(filedir.mkdirs()); //false if directory already exits

// set file length, read only permission for the given file.

 RandomAccessFile rFile = new RandomAccessFile(new File("E:\hai123.txt"), "rw");

Coming up lab 2 on this topic.

Please subscribe my blog for future updates and any doubts comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.