Example. Reading and Writing from a File

[comp1110-99]

In the lecture, we wrote a program that asks the user for some input, and if it has been run before, will display the input it got the last time we ran the program. We picked the name ".storage" for a file that would store the last input in between program runs. The "." at the start of the filename means this file should normally be hidden, as it is meant as internal data for programs, not for users to interact with outside of it. You can still find it and edit it manually if you wish.

void main() { File store = new File(".storage"); if(store.exists()) { try(FileReader fr = new FileReader(store); BufferedReader reader = new BufferedReader(fr)) { String lastSentence = reader.readLine(); IO.println("Last time, you said: "+lastSentence); } catch(IOException e) { IO.println("ERROR: "+e.getMessage()); } } else { IO.println("Hello for the first time!"); } String input = IO.readln("Tell us something new! "); try(FileWriter fw = new FileWriter(store); BufferedWriter writer = new BufferedWriter(fw)) { writer.write(input); //no need to print a newline anyway // short program, no explicit flush needed } catch(IOException e) { IO.println("ERROR: "+e.getMessage()); } }
bars magnifying-glass caret-down plus minus arrow-right xmark