3.2.1.3 Fields, Records and Files. Flashcards
1
Q
Outline the syntax for writing to a file.
A
try { PrintWriter out = new PrintWriter(new FileWriter("M:/samplefile.txt"));
out. println("Knives"); out. println("Forks"); out. println("Spoons");
out.close(); } catch (IOException e) { System.out.println(e.getMessage()); }
2
Q
Outline the syntax for reading from a file.
A
try { Scanner scan = new Scanner(new File("M:/samplefile.txt")); while(scan.hasNextLine()) { System.out.println(scan.nextLine()); } } catch(FileNotFoundException e) { System.out.println(e.getMessage()); }