Introduction to programming in java Lecture 28 File methods
File Constructors // Construct a File object for a file // with name path. Name. File( String path. Name ) The path name of a file is a chain of directory names followed by a file name File file 1 = new File( "C: /My. Files/Programs/Examples/some. File. txt" ); File file 2 = new File( “D: /test. txt" );
Path names • 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.
The exists() method • When a File object is constructed, no check is made to see if the path. Name corresponds to an existing file or directory. • The exists() method tests if a file exists. Do this when a program is about to create a file and you don't want to destroy a previous file of the same name.
Example
Practice Question # 1 • Let us improve the file copy program from the previous lecture so that it tests that: – (1) the destination file does not already exist, and – (2) the source file does exist. – Provide input and output file names from the command line arguments.
There are many more useful methods. If there is something file related you wish to do, check the complete documentation.
Practice Question # 2 • Write a program which prints the list of all files present in the specified path / current directory.