Lesson TwentyInput and OutputPages like these in the tutorial as well as your resume stored on your computer are called data files. The toolbars at the top of your computer screen are called program files. In Java, files like theses are part of the File class. These, however, cannot be opened, processed, or closed by the File class, but they can be shown if they exist, if they are open, what size they are, and when they were last modified. To use this class, you must add import java.io.* at the top of your programs. This contains all the classes needed to access these files. Object is a direct descendant of File. You create a File object by typing a line similar to the one below: File someData = new File("A:\\My Documents\\Java Files\\file.txt"); , where "file.txt" can be found on the path listed on your A: drive. The "io stands for input/output. The reason for the double backslashes "\\" is so that you move to the next folder to search for a file instead of activating an escape sequence. Below are some of the class methods that can be used:
Now, let's create a program that uses some of these methods:
import java.io.*; Now, open a new file in your text editor, type the alphabet, and save it as "data.txt" in the same folder as you did the program above. Once you've done that, run the program. If everything is right, you should see the information about the file. To see what happens if a file doesn't exist, change the file name in the constructor to "text.txt" instead of "data.txt". To see how to find a file on your C: drive, change the constructor so it looks similar to this: File myFile = new File("\\some folder\\My Documents","file choice.extention"); where "some folder" is a folder in "My Documents" and "file choice.extention" is an actual file in that folder (ex. "First.java"). Next, we can create a program that compares two programs to see which one was made or modified most recently and which file is the longest. To do this, you must first open a new document in your text editor, type the first 12 letters in the alphabet, and save it as "data2.txt". Now you can create the following program:
import java.io.*; Question: I like the idea that you can find information about a certain file. What I want to know is how do you write to a file? Answer: Although it seems like we're almost there, there's still much to learn before we get to the big stuff. Next, we'll learn about more advanced file concepts.
If you have a question about any of the lessons, feel free to ask. |