Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 8 ■ WRITING AND READING FILES


Listing 8-8. Creating a directory

package com.apress.java7forabsolutebeginners.examples;

import java.io.File;

public class FileTest {

public static void main(String[] args) {
String testDirectoryName = "C:" + File.separator + "test";
File testDirectory = new File(testDirectoryName);
try {
testDirectory.mkdir();
} catch (Exception e) {
System.out.println("Couldn't create a directory called "
+ testDirectoryName);
System.exit(1);
}
System.out.println("Created a directory called " + testDirectoryName);
}
}

Note that we use the mkdir method rather than the createNewFile method. Windows, requires that
we give special permission to write into the root of the C: drive. Any attempt to create a file called
C:\test on the system would fail. (If we change the path to C:\temp\test, we would get a file called test
(with no extension) in our test directory.) However, we can create a new directory as a child of the root
directory, so the mkdir method works.
You can also create multiple directories, in the form of a longer path to a particular location.
Suppose we want to create a directory called C:\test\test2\test3. We can use the mkdirs method (note
the s on the end) to do so, as shown in Listing 8-9 (with the line that specifies the path and the mkdirs
line highlighted).

Listing 8-9. Creating multiple directories

package com.apress.java7forabsolutebeginners.examples;

import java.io.File;

public class FileTest {

public static void main(String[] args) {
String testDirectoryName = "C:" + File.separator + "test" +
File.separator + "test2" + File.separator + "test3";
File testDirectory = new File(testDirectoryName);
try {
testDirectory.mkdirs();
} catch (Exception e) {
System.out.println("Couldn't create a directory called "
+ testDirectoryName);
System.exit(1);
}
Free download pdf