File Constructors

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

  • For a File object to exist without a file?
    • Yes.
  • For a file to exist without a File object?
    • Yes, all files created in the last few chapters, for example.

File Constructors

A File object is constructed by a program and used while it is running to manipulate a disk file and to get information about it. When a program finishes, the File object is no more, but the file remains on disk (unless the program deliberately deleted it). Here is one of the constructors for File:

File( String pathName  )      // Construct a File object for a file 
                              // with name pathName.

The path name of a file is a chain of directory names followed by a file name. The directory names are separated by a special character. The syntax for directory names, separators, and file names depends on the operating system. Here is a path name for a MS Windows file:

C:/MyFiles/Programs/Examples/someFile.txt

The directory separator character (for MS Windows) is "/". The last part of the path name, following the last separator, is the file name. Here is a Unix path name:

/usr/frodo/Programs/Examples/someFile.txt

Path names are relative or absolute. An absolute path name gives the complete chain of directories from the root directory to the file. A relative path name starts with any directory in the chain and continues to the file. Both relative and absolute path names may be used with the File constructor.

QUESTION 3:

Is the following a correct use of a constructor?

File progFile = new File( "C:/MyFiles/Programs/Examples/someFile.txt" );