CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Files

Text and Binary Files
Files and directories
Examples

Coding the elements in a file path name

  • When coding directory names, you can use a front slash to separate directories.
  • To identify the name and location of a file, you can use:
    • an absolute path name to specify the entire path for a file, or
    • a relative path name to specify the path of the file relative to another directory
  • To create a File object that represents a file on a remote computer, you can use the Universal Naming Convention (UNC). To do that, code two slashes (//) followed by the host name and the share name.

Code that creates a directory if it doesn't already exist

String dirName = "c:/java 1.5/files/";
File dir = new File(dirName);
if (!dir.exists())
    dir.mkdirs();

Code that creates a file if it doesn't already exist

String fileName = "products.txt";
File productsFile = new File(dirName + fileName);
if (!productsFile.exists())
    productsFile.createNewFile();

Code that displays information about a file

System.out.println(
    "File name:      " + productsFile.getName());
System.out.println(
    "Absolute path:  " + productsFile.getAbsolutePath());
System.out.println(
    "Is writable:    " + productsFile.canWrite());

Resulting output

File name:      products.txt
Absolute path:  c:\java 1.5\files\products.txt
Is writable:    true

Code that displays information about a directory

if (dir.exists() && dir.isDirectory())
{
    System.out.println("Directory: " +
        dir.getAbsolutePath());
    System.out.println("Files: ");
    for (String filename : dir.list())
        System.out.println("     " + filename);
}

Resulting output

Directory: c:\java 1.5\files
Files:
     customers.txt
     products.txt

Code that specifies a directory and file on a remote server

String dirName = "//server/c/editorial/customers.txt";
Previous | File class | Examples | Next