Esempio di IO su File

Autore: stefano.russo@unina.it Java

  1. ...
  2. File file = new File("myFile.txt");
  3. try {
  4.     file.createNewFile();   
  5. } catch (IOException x) {   
  6.     System.err.format("createFile error: %s%n", x.getMessage());}
  7.  
  8. //Operazione di lettura
  9. InputStream in = null;
  10. try {
  11.     in = new FileInputStream(file);
  12.     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  13.     String line = null;
  14.     while ((line = reader.readLine()) != null)
  15.         System.out.println(line);
  16. } catch (IOException x) {
  17.     System.err.println(x);
  18. } finally {
  19.     if (in != null) in.close();}
  20. ...