File Interactive Session

Let's look at an example of File. Import the File class from the pa ckpge. >>> from import File

Create an instance of the file obped; that nefers to the properties of the file (c: \\dat\\File. txt). >>> file = File("c:\Xdat\XFile.txt")

Determine if the file is read-only by calling canWrite (). If canWrite () returns 1 (true), the file is read/write. (If you change the erop)ertits of the file to read-only, canWrite () returns 0, that is, false.)

Determine if the file exists. If not, the exists () function returns 0.

Get just the file name without the pa!h.

Get the file path.

Get the path of the parent directory.

In the following code, we'll see if the file is a directory. Then we'll create a File instance that refers to the file's parent directory and test if the directory is actually a directory.

Is the file a directory? (1 means yes; 0 means no)

Creete e File instance that refers to tie file's parent directory, and then see if tie directory is a directory.

>>> directory = file(File.getParent()) >>> directory.isDirectory() 1

Is tie file a file?

Is the directory a file?

ThelastModified() method returns the time, es e Long, which refers to the milli-seconds elepsed since Jan. 1, 1970.

>>> file.lastModified() 93429438 6000L

You can convert the Long to e dete using the following technique. Import the Date class, passing its lest modified velue to its constructor

>>> from java.util import Date >>> date = Date(File.lastModified() ) >>> print date

Tue Aug 10 07:13:06 PDT 1999 Get the length of the file.

Is the class en absolute petl (c: dat\text. tx) or e relative peth (.. \.. \text. txt)?

Delete the file and check to soe if it exists; get its length.

>>> file.length() # Thus its length is zero

Creete e new File instance thet refers to the relative locetion of

>>> file = File ("..\\..\\..\\autoexec.bat")

Check to see if the file exists.

Get the petd (note that it's relative).

>>> file . getPath() '..\\..\\..\\autoexec.bat'

Get the absolute path (tine looks weied).

>>> file.getAbsolutePath()

Get the canonical path (this looks better).

>>> file.getCanonicalPath() 'C:\\AUT OEXEC.BAT'

Was this article helpful?

0 0

Post a comment