import java.io.File; import java.io.FileWriter; /** * Here's some sample code that creates a text file and writes a couple of lines * of text to it. There are some hints in the comments below about what you'll * need to change if you want to work with binary data instead of just strings. * Also, note that I don't do any error-checking in the body of the code -- I * just label main as "throws Exception" so it becomes somebody else's problem. * You'll need to do better than that for the assignment. * * @author brichards */ public class FileExample { public static void main(String[] args) throws Exception { // Get the filename, either as a command-line argument or the default. String filename = "textfile.txt"; if (args.length > 0) { filename = args[0]; } // Create a new File object, though it doesn't necessarily correspond // to an actual file on the disk. File theFile = new File(filename); // Now see if it's already there... if (theFile.exists()) { System.out.println("It already exists. Contents will be overwritten"); } else { System.out.println("Creating new file: "+theFile.getAbsolutePath()); } // File objects don't have read or write methods. Instead, we have to // create some sort of "writer" stream and associate it with the file. // Here I'm using a FileWriter, which is great for strings but not so // great for binary data. You'll want to check out FileOutputStream, // and find a write() method that lets you specify how many bytes from // an array of bytes are to be written. (That same approach will work // for both text and binary data.) FileWriter writer = new FileWriter(theFile); writer.write("hello\n"); writer.write("world"); writer.close(); } }