Le code ci-dessous reprend de manière synthétique ce qui a été présenté dans les slides. Lisez bien les commentaires car ils contiennent plusieurs informations pratiques qui pourront vous servir, notamment pour le laboratoire.
Code pour l’écriture
public static void main(String[] args) { try { // The first argument is the path where the written file will be // This is a absolute path for Windows. In Linux, something // like "~/out.txt" would write the file directly in you home directory FileOutputStream fs = new FileOutputStream("c://temp//out.txt", true); PrintWriter pw = new PrintWriter(fs); // This is the content which will be written INTO the file pw.print("This is the text which will be written"); // We have to close the file when we are done working with it pw.close(); } catch (Exception e) { System.out.println("File can't be written"); e.printStackTrace(); } System.out.println("Writing done"); }
Code pour la lecture
public static void main(String args[]) { try { // The first argument is the path where the file will be read. // This is a absolute path for Windows. In Linux, something // like "~/out.txt" would read the file directly in you home directory FileReader f = new FileReader("c://temp//stuff.txt"); BufferedReader bf = new BufferedReader(f); String line = ""; // Each readLine() call CONSUMES the complete line line = bf.readLine(); System.out.println("The first line of file is :" + line); line = bf.readLine(); System.out.println("The second line of file is :" + line); bf.close(); } catch (Exception e) { e.printStackTrace(); } }