Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 8 ■ WRITING AND READING FILES


Figure 8-1. A test directory

Listing 8-1. Creating an empty file

package com.apress.java7forabsolutebeginners.examples;

import java.io.File;

public class FileTest {

public static void main(String[] args) {
String fileName = "C:\\test\\myFile.txt";
File myFile = new File(fileName);
try {
myFile.createNewFile();
} catch (Exception e) {
System.out.println("Couldn't create " + myFile.getPath());
}
System.out.println("Created " + myFile.getPath());
}
}

If you have a test directory on your C drive, that program creates an empty text file called
myFile.txt in that directory. Figure 8-2 shows the results on my Windows laptop.

Figure 8-2. Test directory with our file

Let's examine the code. First, notice that we have double backslashes (which are escape sequences
that insert a single backslash) for path separators. Using double backslashes is actually bad practice. It
assumes we're running on a Windows (or perhaps DOS) system. But what happens when someone runs
our program on a Unix or Linux system or a Mac? The JVM might figure it out and use the right
Free download pdf