Next page | Contents page |

Files & directories

An object of class java.io.File represents a file or directory as a whole but not its contents.

import java.io.File;
import java.util.Date;

public class FileExample
{
	public static void main (String [] args)
	{
		File f = new File ("somepath\\example.txt");
		long fLength = f.length ();
		Date lastMod = new Date (f.lastModified ());
		String fileName = f.getName ();
		String filePath = f.getPath ();

		if (f.exists () && f.isDirectory ())
		{
			File [] fList = f.listFiles ();
			// Gets a list of all the files in the directory,
			// some of which may also be directories of course

			for (int i = 0; i < fList.length; i++)
			{
				/* ... do something with each file, fList [i] ... */
			}
		}
	} // main
} // FileExample

As always, look at the API documentation to see everything you can do with a File object.

Reading and writing file contents will be covered in a few pages time.

Platform independence

The example above contains something which is not platform-neutral: the use of the backward slash in a file path is very much a Windows thing. On other systems a forward slash is used.

Class File includes some constants which can be used instead of such separators. Use the constants and your code will indeed run on any Java implementation.

So instead of "somepath\\example.txt", write "somepath" + File.separator + "example.txt".

The environment variable known as path also differs between Windows (;) and other systems (:) and for that there is File.pathSeparator.

Next page | Contents page |