Site Map
Useful Tools
Graphing Calc

Scientific Calculator

Files in Java

Folders and Files in Java

import java.io.*;
  • A File object can refer to a Folder or an actual file.
  • How to create a file object:
      File myDir = new File("C:/users/joe/myWork");
    • Note: The prior line does not actually create a file. Rather, all that you did in this line is create an object that represents a path to a folder that may or may not exist on your computer! Just because you decided to create a File object named myDir does not mean that this folder actually exists.
Methods of File and related Class
  • System.getProperty("user.home")
    • This stores the folder of the current user such as
      C:\Users\joe smith
The examples below will refer to the following File objects
File myDir = new File("C:\users\jane smith\documents\myWork\);
File myFile = new File("C:\users\jane smith\documents\abc.doc");

  • Constructor takes a String paramater
    • File myFile = new File("C:\Users\joe smith");
  • String getName()
      Method Call Return
      myDir.getName() myWork
      myFile.getName(); abc.doc
    • String getPath()
    • Method Call Return
      myFile.getPath() C:\users\jane smith\documents\abc.doc
      myDir.getPath(); C:\users\jane smith\documents\myWork
  • boolean exists() Returns true if the folder or file actually exists on the computer
    Useful methods for Directories and for this project in particular
  • listFiles()
    • returns an array of abstract path names (paths) denoting the directories and files inside a particular directory. Returns null if method is called by a file (see first example below myFile.listFiles() ).
    Method Call Return
    myFile.listFiles() null
    myDir.listFiles(); an array of abstract path names representing whatever files and folders are within myDir.

Several self-descriptive methods
  • boolean isFile() self descriptive
  • boolean isDirectory() self-descriptive
  • boolean isHidden()
  • boolean canRead() : returns true if you are permitted to read the file referred to by the file object and false otherwise.
Some of the methods up above are demonstrated in the following class FileDemo.java
import java.io.*;
public class FileDemo {

public static void main(String[] args){
	File myDir = new File("C:/users/jane smith/documents/myWork/");
	File myFile = new File("C:/users/jane smith/documents/abc.doc");


Warm up Mini-project
  • Task #1) Find or create a folder in your H drive that has several files and folders in it.
  • Task #2) Write a class that
    • 1) Creates a file object that refers to the folder in task #1
    • 2) Prints out a list of all the files and folders within this folder