1 / 14

Archivos en disco: motivación

This Java program allows users to copy the content of a file into another file. It also enables users to view the content of a file and display specific lines containing a certain string.

blantons
Download Presentation

Archivos en disco: motivación

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. Archivos en disco: motivación

  2. Problem 1. read lines from keyboard ending with “end” and sabe them in a file named “archivo.txt”. import java.io.*; import java.util.*; class CreateFile { static public void main(String[]args) throws IOException{ Scanner U = new Scanner(System.in); PrintWriter a=new PrintWriter( new FileWriter(“archivo.txt”)); while(true){ String linea=U.readLine(“line ?“); if( linea.equals(“end”) ) break; a.println(linea); } a.close(); } }

  3. Explanations • import java.io.*; • Importsthenecessary clases to manipulate files • classesPrintWriter and FileWriterforwriting files • classesBufferedReader and FileReaderfor Reading files • throwsIOException • Indicatesthat in case of anexception (“error when Reading orwriting”) theprogramaborts. • Withoutthis, theprogramdoesnot compile

  4. PrintWriter a=new PrintWriter(...); • a: objet in memory of thePrintWriterclasswhichrepresnetsthe file and storesinformationaboutitsmaincharacteristicslocation in the disk, size, cursor position, etc. • “archivo.txt”: externalname of the file in disk. • Thesufix .txtisthecommon extensión fortext files (characters, lines). • “opens” (prepares, initializes) file forwriting • If file doesnotexists, itiscreated, ifexists, itis re-written • Locatesthe cursor at thebeginning of theallocatedspaceforthat file (to startwritinginformation)

  5. a.println(linea) • Writes a line in the file • Savesthechatacterscontained in the variable intothe file • Writesan “end-of-line” character • (specialcharacternewlineor \n) • Locatesthe cursor afterthenewline • Example: • a.println(“hola como estás”); • Writes in the disk: • …hola como estás\n • ^ (cursor of the file) • Note. print: methodwritesonlythecharacterswithoutnewline

  6. a.close() • “closes” the file • Writesan “end-of-file” mark in the file (eof) • Freestheresourcesassociated to theobject a • objet a isundefined (null) • example: • a.println(“chao”); a.close(); • …chao\nX • X :end of file mark (different to anycharacter)

  7. Problem 2. Show the content of the file “archivo.txt” import java.io.*; class ReadFile{ static public void main(String[]args) throws IOException { BufferedReader a = new BufferedReader( new FileReader(“archivo.txt”)); while(true){ String linea=a.readLine(); if(linea==null) break; System.out.println(linea); } a.close(); } }

  8. Explanations • BufferedReader a=new BufferedReader(...); • a: objet of theBufferedReaderclasswhichrepresentsthe file • “open” (prepares, inicializes) file forreading • If file doesnotexists, aborts • Ifexists, locatesthe cursos at thebeginning of the file • a.close() • “closes” the file • Ifomitted file closes at theend of theprogram

  9. a.readLine() • Reads a line of the file • Returns a stringwiththecharacteres of the line (withoutthenewlinecharacter) • Locatesthe cursor at thebeginning of thenext line • Example: • a.readLine(); • Reads (and returns) a line fromthe disk file: • hola como estás\n • ^ (cursor of the file) • Note. Ifend of file isdetected (if cursos ispointng to theend of file markwhenstarting to read) a nullvalueisreturned (notthe“null” stringnorthe“” string)

  10. Problem 3. Copy the content of a file into another obtaining from the user the name of both files Scanner U = new Scanner(system.in); System.out.print(“input? “); String input = U.nextLine(); BufferedReader a=new BufferedReader( new FileReader(input); System.out.print(“output? “); String output= U.nextLine(); PrintWriter b=new PrintWriter( new FileWriter(output); String linea; while((linea=a.readLine())!=null) b.println(linea); b.close(); a.close();

  11. Problem 4. show the lines of a file (name given by user) which contain a certain string (also given by the user) System.out.print(“file ?”); String file = U.nextLine(); System.out.print(“string ?”); String p = U.nextLine(); BufferedReader a=new BufferedReader( new FileReader(file))); String linea=null;   while((linea=a.readLine())!=null) if(linea.indexOf(s)>=0) system.out.println(linea); a.close();

  12. Exercise Write a function which returns the number of lines of a file whose name is passed as an argument static public int lines(String x) … } Write a program (main method) which divides the file CS120.txt in two with (almost) the same number of lines. The first half should be written in a file named CS120A.txt and the second in the file CS120B.txt static public void main(String[]args)throws IOException{ int n=lines(“CS120.txt”); BufferedReader a=new BufferedReader(new FileReader(“CS120.txt”)); PrintWriter b=new PprintWriter(new FileWriter(“CS120A.txt”)), c=new PrintWriter(new FileWriter(“CS120B.txt”)); … } Note. If the file has an odd number of lines the first Si el archivo tiene una cantidad impar de líneas, entonces la primera mitad debe contener una línea más que la segunda mitad.

  13. //number of lines of file with name x static public int lines(String x) throws IOException{ BufferedReader a=new BufferedReader( new FileReader(x)); int n=0; while((linea=a.readLine())!=null) ++n; } a.close(); return n; }

  14. static public void main(String[]args)throws IOException{ //get number of lines int n=lines(“CS120”); BufferedReader a=new BufferedReader( new FileReader(“CS120.txt”)); //Split in 2 halfs, copy first part PrintWriter b=new PrintWriter( new FileWriter(“CC1001A.txt”)); for(int i=1; i<=(n+1)/2; ++i) b.println(a.readLine()); b.close(); //copy second half b=new PrintWriter(new FileWriter(“CC1001B.txt”)); for(int i=1; i<=n/2; ++i) b.println(a.readLine()); b.close();

More Related