Apri un file in input; Apri un file in output; While(ci sono altri record in input) leggi un record ; scrivi un record ; Chiudi il file di input; Chiudi il file di output;In Java invece si legge e si scrive non su un oggetto file ma su un oggetto Stream(in italiano si potrebbe tradurre flusso). In apparenza questo complica le cose ma in effetti rende possibile fare le seguenti cose prima impossibili:
import java.io.*; public class Copia { public static void main(String[] args) throws IOException { /* Apri uno stream di input */ FileInputStream in = new FileInputStream(new File("input.java")); /* Apri uno stream di output */ FileOutputStream out = new FileOutputStream(new File("output.java")); while (in.available()!=0)//finche' ci sono dati disponibili in input out.write(in.read());//leggi e scrivi /*Chiudi i due stream*/ in.close(); out.close(); } }Supponiamo ora di voler scrivere dei numeri interi o decimali.Possiamo usare la seguente condotta:
DataOutputStream out = DataOutputStream(new FileOutputStream("output.dat"));O potremmo avere una condotta ancora piu' complessa come:
BufferedOutputStream out =new BufferedOutputStream ( new GZIPOutputStream ( new DataOutputStream ( new FileOutputStream("output.dat"))));dove i dati da scrivere sono anche compressi e scritti usando una memoria tampone(buffer).
file Copy.java
import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); while ( in.ready() ) out.write(in.read()); in.close(); out.close(); } }
FileReader
e FileWriter
:questi vanno avvolti intorno al file di
input e di output rispettivamente.
java.io
che va importato.
file CopyBytes.java
import java.io.*; public class CopyBytes { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); while ( in.available()!=0 ) out.write(in.read()); in.close(); out.close(); } }Nel caso della lettura binaria gli oggetti Stream di base sono
FileInputStream
e FileOutputStream
.
file DataOutTest.java
import java.io.*; public class DataOutTest { public static void main(String[] args) throws IOException { // write the data out DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.dat")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i ++) { out.writeDouble(prices[i]); out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n'); } out.close(); } }
file DataInTest.java
import java.io.*; public class DataInTest { public static void main(String[] args) throws IOException { // read it in again DataInputStream in = new DataInputStream(new FileInputStream("invoice1.dat")); double price; int unit; String desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab desc = in.readLine(); System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); } }Avvolgendo intorno a FileInputStream e FileOutputStream gli oggetti
DataInputStream
e DataOutputStream
possiamo
leggere e scrivere direttamente dei dati primitivi.Infatti questi
oggetti Stream hanno metodi come readDouble, writeInt, etc.
file Copy.java
import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); BufferedReader in = new BufferedReader (new FileReader(inputFile)); BufferedWriter out = new BufferedWriter (new FileWriter(outputFile)); while (in.ready()) out.write(in.read()); in.close(); out.close(); } }
file CopyBytes.java
import java.io.*; public class CopyBytes { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); BufferedInputStream in = new BufferedInputStream( new FileInputStream(inputFile)); BufferedOutputStream out = new BufferedOutputStream ( new FileOutputStream(outputFile)); while (in.available() != 0) out.write(in.read()); in.close(); out.close(); } }
file GZIPcompress.java
import java.io.*; import java.util.zip.*; public class GZIPcompress { public static void main(String args[]) { try { BufferedInputStream in = new BufferedInputStream ( new FileInputStream (args[0])); BufferedOutputStream out = new BufferedOutputStream ( new GZIPOutputStream ( new FileOutputStream(args[0]+".gz"))); while ( in.available()!=0) out.write(in.read()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
file GZIPuncompress.java
import java.io.*; import java.util.zip.*; public class GZIPuncompress { public static void main(String args[]) { try { BufferedOutputStream out = new BufferedOutputStream ( new FileOutputStream ("test")); BufferedInputStream in = new BufferedInputStream ( new GZIPInputStream ( new FileInputStream(args[0]))); while ( in.available()!=0) out.write(in.read()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }Ora la catena di Stream comprende 3 oggetti per avere dei file compressi letti con buffer. Notate che la sequenza deve essere identica in scrittura e lettura.
file Toglim.java
import java.io.*; public class Toglim { public static void main(String[] args) throws IOException { File inputFile = new File("input.java"); File outputFile = new File("output.java"); FileInputStream in = new FileInputStream(inputFile); MyFilterOutputStream out = new MyFilterOutputStream(new FileOutputStream(outputFile)); while (in.available()!=0) out.write(in.read()); in.close(); out.close(); } }
file MyFilterOutputStream.java
import java.io.*; public class MyFilterOutputStream extends FilterOutputStream { public MyFilterOutputStream (OutputStream out) { super(out); } public void write(int b) throws IOException { if (b!=13) out.write(b); } public void write(byte[] b) throws IOException { for (int i=0; i < b.length; i++) write(b[i]); } public void write(byte[] b, int off, int len) throws IOException { for (int i=off; i < len; i++) write(b[i]); } }
FilterOutputStream
possiamo creare
un filtro da applicare ai dati, in quanto nel metodo write della stessa classe ci vengono passati i byte, uno a uno.
file CheckedInputStream.java
import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; public class CheckedInputStream extends FilterInputStream { private Checksum cksum; public CheckedInputStream(InputStream in, Checksum cksum) { super(in); this.cksum = cksum; } public int read() throws IOException { int b = in.read(); if (b != -1) { cksum.update(b); } return b; } public int read(byte[] b) throws IOException { int len; len = in.read(b, 0, b.length); if (len != -1) { cksum.update(b, 0, len); } return len; } public int read(byte[] b, int off, int len) throws IOException { len = in.read(b, off, len); if (len != -1) { cksum.update(b, off, len); } return len; } public Checksum getChecksum() { return cksum; } }
file CheckedOutputStream.java
import java.io.*; public class CheckedOutputStream extends FilterOutputStream { private Checksum cksum; public CheckedOutputStream(OutputStream out, Checksum cksum) { super(out); this.cksum = cksum; } public void write(int b) throws IOException { out.write(b); cksum.update(b); } public void write(byte[] b) throws IOException { out.write(b, 0, b.length); cksum.update(b, 0, b.length); } public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); cksum.update(b, off, len); } public Checksum getChecksum() { return cksum; } }
file CheckedIOTest.java
import java.io.*; public class CheckedIOTest { public static void main(String[] args) throws IOException { Adler32 inChecker = new Adler32(); Adler32 outChecker = new Adler32(); CheckedInputStream in = null; CheckedOutputStream out = null; try { in = new CheckedInputStream( new FileInputStream("farrago.txt"), inChecker); out = new CheckedOutputStream( new FileOutputStream("outagain.txt"), outChecker); } catch (FileNotFoundException e) { System.err.println("CheckedIOTest: " + e); System.exit(-1); } catch (IOException e) { System.err.println("CheckedIOTest: " + e); System.exit(-1); } int c; while ((c = in.read()) != -1) out.write(c); System.out.println("Input stream check sum: " + inChecker.getValue()); System.out.println("Output stream check sum: " + outChecker.getValue()); in.close(); out.close(); } }In questo caso costruiamo 2 stream, uno per l'imput e l'altro per l'output. Questi stream utilizzano i metodi dell'oggetto
Adler32
(preso da Internet)
per calcolare il valore checksum che permette
di verificare l'integrita' del file dopo la copia. Tutto questo e' fatto aggiungendo le classi alla nostra catena di Stream.
file BunchOfRandoms.java
import java.io.*; public class BunchOfRandoms implements Serializable { // Generate a random value private static int r() { return (int)(Math.random() * 10); } private int data[]; // Constructor public BunchOfRandoms() { data = new int[r()]; for (int i=0; i < data.length; i++) data[i]=r(); } public void printout() { System.out.println("This BunchOfRandoms has "+data.length+" random ints"); for (int i=0; i < data.length; i++) System.out.print(data[i]+":"); System.out.println(); } }
file SerializeOut.java
import java.io.*; import java.util.*; public class SerializeOut { public static void main (String args[]) throws IOException { BunchOfRandoms b1 = new BunchOfRandoms(); BunchOfRandoms b2 = new BunchOfRandoms(); ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream("objects.dat")); Date now = new Date(System.currentTimeMillis()); out.writeObject(now); out.writeObject(b1); out.writeObject(b2); out.close(); System.out.println("I have written:"); System.out.println("A Date object: "+now); System.out.println("Two bunchs of randoms"); b1.printout(); b2.printout(); } }
file SerializeIn.java
import java.io.*; import java.util.*; public class SerializeIn { public static void main (String args[]) throws IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream ( new FileInputStream("objects.dat")); Date d1 = (Date)in.readObject(); BunchOfRandoms br1 = (BunchOfRandoms)in.readObject(); BunchOfRandoms br2 = (BunchOfRandoms)in.readObject(); System.out.println("I have read:"); System.out.println("A Date object: "+d1); System.out.println("Two bunchs of randoms"); br1.printout(); br2.printout(); } }
ObjectInputStream
e ObjectOutputStream
aggiunti alla
nostra sequenza di oggetti Stream, permettono
la lettura/scrittura di oggetti. Questi oggetti
devono tutti implementare l'interfaccia Serializable
ooObj
.
file WindowSerializeOut.java
import java.awt.*; import java.awt.event.*; import java.io.*; public class WindowSerializeOut implements ActionListener { Frame f; public void actionPerformed (ActionEvent ev) { try { ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream ("status.dat")); out.writeObject(f); out.close(); System.out.println("Window serialized"); } catch (IOException e) { e.printStackTrace(); } } public void createFrame () { f = new Frame(); f.setLayout (new FlowLayout()); f.setLocation(100,100); f.add (new Button("A button")); Button b = new Button ("Serialize Frame"); f.add(b); b.addActionListener(this); f.add (new TextField("This is a textfield")); f.pack(); f.show(); } public static void main (String args[]) { WindowSerializeOut w = new WindowSerializeOut(); w.createFrame(); } }
file WindowSerializeIn.java
import java.awt.*; import java.io.*; public class WindowSerializeIn { public static void main (String args[]) throws IOException, ClassNotFoundException{ ObjectInputStream in = new ObjectInputStream ( new FileInputStream ("status.dat")); Frame f = (Frame)in.readObject(); in.close(); System.out.println("Window retrieved"); f.show(); } }Quasi tutti gli oggetti di libreria Java inclusi quelli grafici sono serializzabili e quindi possono essere scritti e letti.
file Login.java
import java.io.*; public class Login implements Serializable { private String user; private transient String password; public Login() {} public Login (String u, String p) { user = u; password = p; } public void printout () { if (user != null) System.out.println ("User name is: "+user); else System.out.println ("User name not defined"); if (password != null) System.out.println ("Password is: "+password); else System.out.println ("Password not defined"); } }
file MyApplication.java
import java.io.*; public class MyApplication { public static void main (String[] args) throws IOException, ClassNotFoundException { Login l1 = new Login("teacher", "class99java"); System.out.println ("This is the object created in memory"); l1.printout(); ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream ("login.dat")); out.writeObject(l1); out.close(); // We crate another login object from the stored one ObjectInputStream in = new ObjectInputStream ( new FileInputStream ("login.dat")); Login l2 = (Login)in.readObject(); System.out.println("This is the object created from serialization"); l2.printout(); in.close(); } }In Java ci sono 2 modi per evitare che dei dati appartenenti a un'oggetto siano scritti in output:il primo modo qui implementato consiste nel definire questi dati
transient
.
Il secondo modo,implementato nel successivo programma, consiste nel far implementare all'oggetto l'interfaccia Externalizable
e in tal modo
indicando esattamente i dati da leggere e scrivere.
file Blip.java
import java.io.*; public class Blip implements Externalizable { int i; String s; public Blip() { System.out.println("Blip's default constructor"); i=0; s=""; } public Blip (String x, int a) { System.out.println("Blip's constructor with data"); s=x; i=a; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { s = (String)in.readObject(); } public void writeExternal (ObjectOutput out) throws IOException { out.writeObject(s); } public void printout() { System.out.println ("This blip has an int: "+i); System.out.println ("This blip has a string: "+s); } }
file serializeOutBlips.java
import java.io.*; public class SerializeOutBlips { public static void main (String args[]) throws IOException { Blip b = new Blip ("Hello class", 21); b.printout(); ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream ("blips.dat")); out.writeObject(b); out.close(); } }
file SerializeInBlips.java
import java.io.*; public class SerializeInBlips { public static void main (String args[]) throws IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream ( new FileInputStream ("blips.dat")); Blip b = (Blip)in.readObject(); b.printout(); in.close(); } }I metodi
readExternal
e writeExternal
dell'interfaccia Externalizable ci permettono di scegliere i dati da scrivere/legge
all'atto della serializzazione dell'oggetto.
import java.awt.*; import java.applet.*; import java.io.*; import java.net.*; public class GetData extends Applet { URL theURL; TextArea ta = new TextArea("In attesa di connessione...",30,70); public void init() { try { this.theURL = new URL(getCodeBase (),"getdata.txt"); } catch ( MalformedURLException e) { System.out.println("Bad URL: " + theURL); } setLayout(new BorderLayout()); add("Center",ta); URLConnection conn; BufferedReader data; String line; StringBuffer buf = new StringBuffer(); try { conn = this.theURL.openConnection(); conn.connect(); ta.setText("Connessione aperta..."); data = new BufferedReader(new InputStreamReader( conn.getInputStream())); ta.setText("Sto leggendo..."); while ((line = data.readLine()) != null) { buf.append(line + "\n"); } ta.setText(buf.toString()); } catch (IOException e) { System.out.println("IO Error:" + e.getMessage()); } } }
conn.getInputStream())
ma per il resto le tecniche di I/O sono identiche.
public class mm extends ConsoleApplet { public void init() { title = "mm"; super.init(); } protected void program() { int trial; int i,ntri; int icif[] = new int [5]; int itri[] = new int [5]; int ieq = 0; int ipres = 0; int starttime = 0,totaltime; for (i=0;i<5;i++) { icif [i] = (int)(Math.random()*10); } ntri = 0; while(ieq < 5){ ntri = ntri + 1; console.putln(" "); trial = console.getlnInt(); if(ntri == 1) starttime=(int)System.currentTimeMillis(); console.put(" "); for (i=0;i<5;i++) { itri[4-i] = trial % 10; trial = trial / 10; } ieq = confr1(itri,icif); ipres = confr2(itri,icif); console.put(ieq);console.put(ipres); } totaltime = ((int)System.currentTimeMillis() - starttime)/1000; console.putln(" ");console.put(ntri); console.put(" ");console.put(totaltime); console.put(" ");console.put(totaltime*ntri); } protected int confr1(int itri[],int icif[]) { int i,ieq; ieq = 0; for (i=0;i<5;i++) { if (itri[i] == icif[i]) ieq = ieq + 1; } return(ieq); } protected int confr2(int itri[],int icif[]) { int i,ipres; int icif1[] = new int [5]; int icif2[] = new int [5]; ipres = 0; for (i=0;i<5;i++) { icif1[i] = icif[i]; icif2[i] = icif[i]; if (itri[i] == icif[i]) icif1[i] = -1; } for (i=0;i<5;i++) { if(icif1[i] != -1) { for (int j=0;j<5;j++) { if ((icif1[j] != -1) && (icif2[j] != -1)) { if (itri[i] == icif[j]) icif2[j] = -1; if (itri[i] == icif[j]) ipres = ipres + 1; if (itri[i] == icif[j]) break ; } } } } return(ipres); } }Java non da la possibilita' di scrivere quei brevi programmi tipo:
read a,b c = a +b write cQui la difficolta' viene superata utilizzando 3 classi prese da Internet:in particolare la classe
ConsolePanel
ha tutta una serie di metodi
get
e put
che permettono di leggere e scrivere
nella finestra dell'applet. Utilizzando queste classi possiamo scrivere
il programma prima visto nel modo seguente:
public class somma extends ConsoleApplet { public void init() { title = "somma"; super.init(); } protected void program() { float a,b,c; console.putln("Scrivi due numeri"); a = console.getFloat(); b = console.getlnFloat(); c = a + b; console.put("La somma e'");console.putln(c); } }Ed ecco lo stesso programma scritto come applicazione:
import java.io.*; import java.util.*; public class sommap { public static void main(String f[]) { BufferedReader br = new BufferedReader( new InputStreamReader( System.in )); StringTokenizer st; System.out.println("Scrivi 2 numeri"); try { String s = br.readLine(); // Read the whole line st = new StringTokenizer(s); float a = new Float(st.nextToken()).floatValue(); float b = new Float(st.nextToken()).floatValue(); float c = a + b; System.out.println("la somma e' " + c); } catch (IOException ioe) { System.out.println( "IO error:" + ioe ); } } }Java ha sempre 3 stream aperti System.in,System.out e System.err
import java.io.*; class execInput { public static void main(String Argv[]) { try { String ls_str; Process ls_proc = Runtime.getRuntime().exec("/bin/ps -eaf "); DataInputStream ls_in = new DataInputStream(ls_proc.getInputStream()); try { while ((ls_str = ls_in.readLine()) != null) { if(ls_str.indexOf("nobody") == 0 ) { System.out.println(ls_str); String procnum = "/bin/kill -9 " +ls_str.substring(6,14); if(ls_str.indexOf("httpd") >= 0) { System.out.println(procnum); Process p = Runtime.getRuntime().exec(procnum); // System.out.println("return code: " + p.exitValue()); } } } } catch (IOException e) { System.exit(0); } //this will catch any problems with the exec } catch (IOException e1) { System.err.println(e1); System.exit(1); } System.exit(0); } }
import java.awt.*; import java.awt.event.*; import java.applet.*; import java.net.*; public class DisplayDoc extends Applet implements ActionListener { URL theURL; Button b; public void init() { b = new Button("Clicca qui per collegarti al Java Tutorial"); b.addActionListener(this); add(b); String url = "http://java.sun.com/docs/books/tutorial/index.html"; try { this.theURL = new URL(url); } catch ( MalformedURLException e) { System.out.println("Bad URL: " + theURL); } } public void actionPerformed(ActionEvent e) { getAppletContext().showDocument(theURL); } }