SHOW:
|
|
- or go back to the newest paste.
| 1 | import java.io.*; | |
| 2 | import java.util.Scanner; | |
| 3 | /** | |
| 4 | * Clase CopiaFich. Entregable temas 3 y 4. | |
| 5 | * | |
| 6 | * @author (PRG. ETSINF. UPV) | |
| 7 | * @version (Curso 16/17) | |
| 8 | */ | |
| 9 | public class CopiaFich {
| |
| 10 | ||
| 11 | /** Devuelve un descriptor File copia de f (misma ubicacion en el | |
| 12 | * sistema y mismo nombre del fichero), salvo que el nombre del | |
| 13 | * fichero se inserta la palabra -copia (antes de la extension). | |
| 14 | */ | |
| 15 | public static File descriptorCopia(File f) {
| |
| 16 | String nombre = f.getName() ; // nombre del fichero | |
| 17 | String padre = f.getParent() ; // padre del fichero | |
| 18 | File filePadre = new File(padre); | |
| 19 | String nuevoNombre = ""; | |
| 20 | ||
| 21 | // Calculo del nombre del fichero copiado: | |
| 22 | int posPunto = 0; | |
| 23 | for(int i = 0; i < nombre.length() -1; i++) {
| |
| 24 | if(nombre.charAt(nombre.length() -1 -i) == '.') {
| |
| 25 | posPunto = nombre.length() -1 -i; | |
| 26 | } | |
| 27 | } | |
| 28 | nuevoNombre += nombre.substring(0,posPunto); | |
| 29 | nuevoNombre += "-copia"; | |
| 30 | nuevoNombre += nombre.substring(posPunto, nombre.length()); | |
| 31 | ||
| 32 | ||
| 33 | File fC = new File(filePadre, nuevoNombre); | |
| 34 | return fC; | |
| 35 | } | |
| 36 | ||
| 37 | /** Recibe el nombre de un fichero de texto y obtiene una copia en | |
| 38 | * la misma ubicacion del sistema. | |
| 39 | */ | |
| 40 | public static void main(String[] args) {
| |
| 41 | if (args.length != 1) {
| |
| 42 | System.out.println("Atencion: Se debe pasar el nombre el fichero a copiar.");
| |
| 43 | System.exit(0); | |
| 44 | } | |
| 45 | ||
| 46 | String nombreE = args[0]; // nombre completo del fichero de entrada | |
| 47 | File fEnt = new File(nombreE); // File del fichero a copiar | |
| 48 | File fSal = descriptorCopia(fEnt); // File del fichero copia resultante | |
| 49 | Scanner scan = null; | |
| 50 | PrintWriter pw = null; | |
| 51 | try{
| |
| 52 | scan = new Scanner(fEnt); | |
| 53 | pw = new PrintWriter(fSal); | |
| 54 | } catch (FileNotFoundException e1) {
| |
| 55 | System.out.println("Error al abrir ficheros.");
| |
| 56 | } //finally {
| |
| 57 | ||
| 58 | ||
| 59 | // Lectura del fichero a copiar y escritura en el fichero resultante: | |
| 60 | int lineas = 0; | |
| 61 | ||
| 62 | while (scan.hasNext()) {
| |
| 63 | pw.println(scan.nextLine()); | |
| 64 | lineas++; | |
| 65 | } | |
| 66 | scan.close(); | |
| 67 | pw.close(); | |
| 68 | System.out.println(fEnt.getName() + " se ha copiado en " + fSal.getName()); | |
| 69 | System.out.println("(" + lineas + ") lineas");
| |
| 70 | ||
| 71 | //} | |
| 72 | ||
| 73 | } | |
| 74 | } |