TopStreamsReading and writing files

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.


TopStreamsReading and writing files