1 / 23

Programare Orientata Obiect

Programare Orientata Obiect. Curs 11 Pachetul I/O. Continutul cursului. Introducere Platforma Java, Clase si Obiecte Modificatori, Constructori Pachete. Incapsularea datelor Mostenirea / Extinderea claselor Conversii de date. Clase si metode abstracte Interfete Exceptii (I)

fraley
Download Presentation

Programare Orientata Obiect

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programare Orientata Obiect Curs11 Pachetul I/O Curs 11

  2. Continutul cursului • Introducere • Platforma Java, Clase si Obiecte • Modificatori, Constructori • Pachete. Incapsularea datelor • Mostenirea / Extinderea claselor • Conversii de date. Clase si metode abstracte • Interfete • Exceptii (I) • Exceptii (II) • Fire de executie • Pachetul I/O Curs 11

  3. Curs 11 • Pachetul I/O 1.1 Privire de ansamblu 1.2 Fluxuri de tip byte 1.3Fluxuri de tip caracter 1.4 Conversiiintrefluxuri de date 1.5 Accesareafisierelor 1.6 Clasa File 1.7 Eficientizareatransferului de date 1.8 Exemple 1.9 Link-uri utile Curs 11

  4. C11. Pachetul I/O • 1.1 Privire de ansamblu • Aplicatiile au nevoie de modalitati de: • Citirea datelordintr-o sursaexterna (fisiere, retea, memoriesaualtaaplicatie) • Scriere a datelor la o destinatieexterne(fisiere, retea, memoriesaualtaaplicatie) • Citirea/scrierea de date se face prinintermediulunorcanale de comunicatiesaufluxurisirespectaurmatorulalgoritm: • deschide canal comunicatie • while (mai sunt informatii) { • citeste/scrie informatie; • } • inchide canal comunicatie;

  5. C11. Pachetul I/O • 1.1 Privire de ansamblu • Fluxuri standard de intrare-iesire: • intrare standard • iesire standard • iesire standard pentru erori • Intrarea si iesirea standard sunt reprezentate de obiecte pre-create ce descriu fluxuri de date care comunica cu dispozitivele standard ale sistemului. • Aceste obiecte sunt definite publice in clasa System si sunt: • • System.in - fluxul standard de intrare • • System.out - fluxul standard de iesire • • System.err - fluxul standard pentru erori

  6. C11. Pachetul I/O • 1.1 Privire de ansamblu • Pachetul I/O (java.io) contineclase care definescoperatiile de intrare-iesirecafluxuri(streams) de date, adicasecventestructurate de date care au o sursa (fluxuri de intrare) sau o destinatie(fluxuri de iesire). • Tipuri de fluxuri de date: • Fluxuri de tip byte • Pe 8 biti (data-based) • Fluxuri de intraresifluxuri de iesire • Fluxuri de tip caracter • Pe 16 biti (text-based) • Fluxuri de citiresifluxuri de scriere

  7. C11. Pachetul I/O • 1.2 Fluxuride tip byte • Se folosescdouaclaseabstracte: InputStreamsiOutputStream • Citireadatelor: • ClasaInputStreamdefineste o metodaabstracta: • public abstract int read() throws IOException • Clasele care mostenescclasaInputStreamimplementeazametodaread(). • Exemplu: ClasaFileInputStreamcare citeste date (de tip byte) dintr-un fisier. • ClasaInputStreamcontinesi o serie de metodeneabstracte care permit citireaunui sir de date de tip byte saupentruignorareaunuinumar de bytes.

  8. C11. Pachetul I/O • 1.2 Fluxuride tip byte • Scriereadatelor: • ClasaOutputStreamdefineste o metodaabstracta: • public abstract void write(int b) throws IOException • Clasele care mostenescclasaOutputStreamimplementeazametodawrite(). • Exemplu: ClasaFileOutputStreamcare scrie date (de tip byte) intr-un fisier. • ClasaOutputStreamcontinesi o serie de metodeneabstracte care permit scriereaunui sir de date de tip byte • Important! Dupascriereasaucitireadatelorfluxul de date trebuieinchisfolosindmetodaclose(), pentru a eliberarearesurselorceapartinsistemului de operare.

  9. C11. Pachetul I/O • 1.2 Fluxuride tip byte import java.io.*; class CountBytes { • public static void main(String[] args) throws IOException { • FileInputStream in = new FileInputStream(args[0]); • int total = 0; • while (in.read() != -1) • total++; • in.close(); • System.out.println(total + ” bytes”); • } • } import java.io.*; class TranslateByte { • public static void main(String[] args) throws IOException { • byte from = (byte)args[0].charAt(0); • byte to = (byte)args[1].charAt(0); • int x; • while((x = System.in.read()) != -1) • System.out.write(x == from ? to : x); • } • }

  10. C11. Pachetul I/O • 1.3 Fluxuride tip caracter • Se folosescdouaclaseabstracte: Reader siWriter • Fiecareclasa are metodesimilare cu celepentrufluxuri de tip byte (InputStreamsiOutputStream) • Clasele standard pentruoperatii de intrare-iesire- System.in, System.outsiSystem.err – au fostimplementateinainte de inventareafluxuri de tip caracter. Acesteautilizeazafluxuri de tip byte, desi, din punct de vedere logic, artrebuisa fie de tip caracter.

  11. C11. Pachetul I/O • 1.4 Conversiiintrefluxuri • Conversiaintre date din fluxuri de tip byte sifluxuri de tip caracter se face cu ajutorulclaselorInputStreamReadersiOutputStreamWriter • public InputStreamReader(InputStream in) • public InputStreamReader(InputStream in, String encoding) • public OutputStreamWriter(OutputStream out) • public OutputStreamWriter(OutputStream out, String encoding) • Metodaread() a claseiInputStreamReaderciteste date in format byte din fluxulasociat (InputStream) si le converteste in caractere • Metodawrite() a claseiOutputStreamWriterconvertestedatele e tip caracter in format byte si le transmitefluxului de iesire (OutputStream)

  12. C11. Pachetul I/O • 1.5 Accesareafisierelor • Accessecvential • Se pot folosiclaseleFileInputStream, FileOutputStream, FileReadersiFileWriter, pentruoperatii de intrare-iesire • Fiecareclasa are 3 tipuri de constructori: • Un constructor care primeste o valoare de tip String care reprezintanumeleunuifisier • Un constructor care primeste un obiect de tip Filecedescrie un fisier • Un constructor care primeste un obiect de tip FileDescriptor

  13. C11. Pachetul I/O • 1.5 Accesareafisierelor • Accesaleator • ClasaRandomAccessFilepermite ca operatiile de citiresiscrieresa se faca la o locatiespecificata in cadrulunuifisier • Un indicator de fisierestefolositpentru a indicapozitia de unde se incepecitireasauscriere • ClasaRandomAccessFile nu este o subclasa a claselorInputStream, OutputStream, ReadersauWriterpentru ca permiteatatoperatii de scriere cat si de citire in cadrulaceluiasiobiect • ClasaRandomAccessFilepoatelucraatat cu fluxuri de tip byte cat si cu caractere.

  14. C11. Pachetul I/O • 1.5 Accesareafisierelor import java.io.*; class Filecopy { public static void main(String args[]) { RandomAccessFile fh1 = null; RandomAccessFile fh2 = null; long filesize = -1; byte[] buffer1; try { fh1 = new RandomAccessFile(args[0], “r”); fh2 = new RandomAccessFile(args[1], “rw”); } catch (FileNotFoundException e) { System.out.println(“File not found”); System.exit(100); } try { filesize = fh1.length(); intbufsize = (int)filesize/2; buffer1 = new byte[bufsize]; fh1.readFully(buffer1, 0, bufsize); fh2.write(buffer1, 0, bufsize); } catch (IOException e) { System.out.println("IO error occurred!"); System.exit(200); } } }

  15. C11. Pachetul I/O • 1.6 Clasa File • Aceastaclasa se folosestepentru a accesainformatiidespre un fisiersau un director • Un obiect de tip Filereprezintacaleacatre un fisiersi nu acceseazaefectivfisierul • Constructori: • public File( String name) • public File( String pathToName, String name) • public File( File directory, String name) • Metode: • booleancanRead() / booleancanWrite() • boolean exists() • booleanisFile() / booleanisDirectory() / booleanisAbsolute() • String getAbsolutePath() / String getPath() • String getParent() • String getName() • long length() • long lastModified()

  16. C11. Pachetul I/O • 1.7 Eficientizareatransferului de date • ClasaBufferedReaderciteste date de la un flux de caracteresi le stocheazatemporarpentru a realiza o citiremaieficienta a caracterelorsi a sirurilor de caractere • De exemplu: • Se poatefolosi un obiect de tip InputStreamReader ca intrarepentruBufferedReader BufferedReader in • = new BufferedReader(new InputStreamReader(System.in)); • Se poatefolosi un obiect de tip FileReaderca intrarepentruBufferedReader BufferedReader in • = new BufferedReader(new FileReader(“fileName”)); • In final se poateapelapentruobiectele de tip BufferedReadermetodareadLine() care citestefluxul de caracterelinie cu linie

  17. C11. Pachetul I/O • 1.7 Eficientizareatransferului de date import java.io.*; public class EfficientReader { public static void main (String[] args) { try { BufferedReaderbr = new BufferedReader(new FileReader(args[0])); // get line String line = br.readLine(); // while not end of file… keep reading and displaying lines while (line != null) { System.out.println("Read a line:"); System.out.println(line); line = br.readLine(); } // close stream br.close(); } catch(FileNotFoundExceptionfe) { System.out.println("File not found: “+ args[0]"); } catch(IOExceptionioe) { System.out.println("Can’t read from file: “+args[0]); } } }

  18. C11. Pachetul I/O • 1.8 Exemple (I) • import java.io.*; • public class CopiereFisiere • { • static FileInputStreamfsursa; • static FileOutputStreamfdest; • public static void main( String args[]) • { if (args.length != 2) • { System.out.println("Utilizare: java CopiereFisieresursadestinatie"); • System.exit(1); • } • try • { fsursa = new FileInputStream(args[0]); • fdest = new FileOutputStream(args[1]); • copiere(fsursa,fdest); • fsursa.close(); • fdest.close(); • }

  19. C11. Pachetul I/O • 1.8 Exemple (I) • catch (FileNotFoundException e) • { System.out.println("Nu existafisierul " + args[0]); • System.exit(2); • } • catch (IOException e) • { System.out.println(" Eroarecopiere"); • } • } • public static void copiere(InputStream sin, OutputStreamsout) • throws IOException • { byte buffer[] = new byte[1024]; • intbytesCititi; • while( (bytesCititi = sin.read(buffer)) > 0) • sout.write(buffer,0,bytesCititi); • } • }

  20. C11. Pachetul I/O • 1.8 Exemple (II) • import java.io.*; • class ScriePrime • { public static void main(String args[]) • { int prime[] = new int[400]; • int index = 0, nr = 2; • while ( index < 400) • { if (estePrim(nr)) • prime[index++] = nr; • nr++; • } • try • { FileOutputStreamfout = new FileOutputStream("NrPrime.dat"); • BufferedOutputStream buffer = new BufferedOutputStream(fout); • DataOutputStream date = new DataOutputStream(buffer); • for(inti=0;i<400;i++) • date.writeInt(prime[i]); • date.close(); • }

  21. C11. Pachetul I/O • 1.8 Exemple (II) • catch(IOExceptione) • { System.out.println("Eroare " + e); • System.exit(1); • } • System.exit(0); • } • public static booleanestePrim(int nr) • { double radical = Math.sqrt(nr); • for(inti=2;i<= radical;i++) • if (nr%i == 0) • return false; • return true; • } • }

  22. C11. Pachetul I/O • 1.9 Link-uri utile: • Reading and Writing • http://java.sun.com/docs/books/tutorial/essential/io/index.html • File Access and Permissions • http://developer.java.sun.com/developer/onlineTraining/Programming/BasicJava1/data.html

  23. Continutul cursului • Introducere • Platforma Java, Clase si Obiecte • Modificatori, Constructori • Pachete. Incapsularea datelor • Mostenirea / Extinderea claselor • Conversii de date. Clase abstracte • Interfete • Exceptii (I) • Exceptii (II) • Fire de executie • Pachetul I/O • Pachetul AWT Curs 11

More Related