mercoledì 3 marzo 2010

Esercizio sugli stream-svolto in classe

Data una lista di nome, cognome, data di nascita di alcune persone messe in ordine verticale, posizionarle in modo orizzontale.


//per intercettare il tipo di errore input-output degli stream
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
public class Stream {
public static void main(String[]args)throws IOException{
/*if(args.length!=4){
System.out.println("Usage: java CambiaFormato ");
System.exit(-1);
}
*/

if(args.length!=4){
String s="Usage:java CambiaFormato ";
throw new IllegalArgumentException(s);
}
FileInputStream FIn=null;
FileOutputStream FOut=null;
InputStreamReader inStream=null;
OutputStreamWriter outStream = null;
BufferedReader buffRead =null;
BufferedWriter buffWriter=null;
// null sta per vuoti
try{
FIn=new FileInputStream(args[0]);
FOut=new FileOutputStream(args[2]);

inStream=new InputStreamReader(FIn,args[1]);
outStream=new OutputStreamWriter(FOut,args[3]);

buffRead= new BufferedReader(inStream);
buffWriter=new BufferedWriter(outStream);
String temp=null; // temp=stringa temporanea-una volta carica il nomr, poi cognome ecc
String nome=null;
String cognome=null;
String data=null;
int count =1; // per contare che riga sto leggendo
while((temp=buffRead.readLine())!= null){
if((count %3)==1)
nome =temp;

else if((count %3)==2)
cognome =temp;

else{
data =temp;
buffWriter.write(nome+";"+cognome+";"+data+"\r\n");
}
count++;
}
System.out.println("Copia effettuata,lette"+(count-1)+"righe");
}catch(FileNotFoundException fnfe){
System.out.println("Errore nelle crazioni dei flussi di input e/o output di byte da/verso i file");
System.out.println(fnfe.getMessage());
}catch(UnsupportedEncodingException uee){
System.out.println("Codifiche dei flussi di input e/o di output di caratteri errate");
System.out.println(uee.getMessage());
}catch(IOException ioe){
System.out.println("Errore in fase di lettura e/o scrittura di caratteri");
System.out.println(ioe.getMessage());
}
finally{
if(buffWriter!=null)
buffWriter.close();
if(buffRead!=null)
buffRead.close();
if(outStream!=null)
outStream.close();
if(buffWriter!=null)
buffWriter.close();
if(buffWriter!=null)
buffWriter.close();
if(buffWriter!=null)
buffWriter.close();
}

}

}

Nessun commento: