Reading and writing files |
To read from a file:
Here is some code from the Short words demo that does all of these steps:
// Open the file wordReader = new BufferedReader(new FileReader(DICTIONARY_FILE)); // get the first line of the file words[numWords] = wordReader.readLine(); // Read words until we run out of words or the array becomes full while (words[numWords] != null && numWords < MAX_WORDS) { // Display the word allWordsArea.append(words[numWords] + "\ n"); numWords++; // get the next line from the file words[numWords] = wordReader.readLine(); } wordReader.close();
Lots of things can go wrong working with files. For example,
Because of these problems, file operations are generally surrounded by a try statement so these exceptions (IOException) can be handled. These exceptions are a little different than other exceptions we have seen this semester. These are checked exceptions, meaning that Java requires us to handle them. If we don't we will get a compiler error.
Writing a file requires similar steps:
Here is code from the ShortWords demo to write a file:
// open the stream to write to the file FileWriter wordWriter = new FileWriter(SHORT_WORDS_FILE); // write the fixed length words wordWriter.write(shortWordsArea.getText()); // Close the file wordWriter.close();
This code would again be within a try statement to handle the IOExceptions that might occur. See the complete example for details.
Reading and writing files |