The program below simply reads a file called FileTest1.java( itself) and prints it to the console
Two methods of the Scanner class were used here hasNext and next.
You should be able to see what these methods are doing here if not then you can check with the Scanner page on sun's Java API.
This is the recommended way of reading a file these days.
To write to a file, use the FileWriter class wrapped in a BufferedWriter
Notice the use of System.getPrope rty("line.separ ator"); to write a return
This method of opening a file overrides the data that was on the file.
To open the file in append mode, simply use
These approaches should not be used for manipulating .doc, pdf, xls e.t.c Instead one should use more specific packages
Code:
import java.util.Scanner; import java.io.*; class FileTest1 { public static void main(String args[]) { Scanner inputFile = null; try { inputFile = new Scanner(new File("FileTest1.java")); while(inputFile.hasNext()) { System.out.println(inputFile.next()); } } catch(FileNotFoundException fNFE) { System.out.println("The file was not found"); } finally { inputFile.close(); } } }
You should be able to see what these methods are doing here if not then you can check with the Scanner page on sun's Java API.
This is the recommended way of reading a file these days.
To write to a file, use the FileWriter class wrapped in a BufferedWriter
Code:
public static void writeFile(String fileName) { BufferedWriter br = null; try { br = new BufferedWriter(new FileWriter(fileName)); String[] semiFinals = {"Australia", "West Indies", "South Africa", "Sri Lanka"}; for(String s : semiFinals) { br.write(s); br.write(System.getProperty("line.separator")); } br.close(); } catch(IOException iO) { System.out.println("The file could not be created/opened/closed"); } }
Notice the use of System.getPrope rty("line.separ ator"); to write a return
This method of opening a file overrides the data that was on the file.
To open the file in append mode, simply use
Code:
br = new BufferedWriter(new FileWriter(fileName, true));
Comment