Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Scanner;
- /**
- * Clase CopiaFich. Entregable temas 3 y 4.
- *
- * @author (PRG. ETSINF. UPV)
- * @version (Curso 16/17)
- */
- public class CopiaFich {
- /** Devuelve un descriptor File copia de f (misma ubicacion en el
- * sistema y mismo nombre del fichero), salvo que el nombre del
- * fichero se inserta la palabra -copia (antes de la extension).
- */
- public static File descriptorCopia(File f) {
- String nombre = f.getName() ; // nombre del fichero
- String padre = f.getParent() ; // padre del fichero
- File filePadre = new File(padre);
- String nuevoNombre = "";
- // Calculo del nombre del fichero copiado:
- int posPunto = 0;
- for(int i = 0; i < nombre.length() -1; i++) {
- if(nombre.charAt(nombre.length() -1 -i) == '.') {
- posPunto = nombre.length() -1 -i;
- }
- }
- nuevoNombre += nombre.substring(0,posPunto);
- nuevoNombre += "-copia";
- nuevoNombre += nombre.substring(posPunto, nombre.length());
- File fC = new File(filePadre, nuevoNombre);
- return fC;
- }
- /** Recibe el nombre de un fichero de texto y obtiene una copia en
- * la misma ubicacion del sistema.
- */
- public static void main(String[] args) {
- if (args.length != 1) {
- System.out.println("Atencion: Se debe pasar el nombre el fichero a copiar.");
- System.exit(0);
- }
- String nombreE = args[0]; // nombre completo del fichero de entrada
- File fEnt = new File(nombreE); // File del fichero a copiar
- File fSal = descriptorCopia(fEnt); // File del fichero copia resultante
- Scanner scan = null;
- PrintWriter pw = null;
- try{
- scan = new Scanner(fEnt);
- pw = new PrintWriter(fSal);
- } catch (FileNotFoundException e1) {
- System.out.println("Error al abrir ficheros.");
- } //finally {
- // Lectura del fichero a copiar y escritura en el fichero resultante:
- int lineas = 0;
- while (scan.hasNext()) {
- pw.println(scan.nextLine());
- lineas++;
- }
- scan.close();
- pw.close();
- System.out.println(fEnt.getName() + " se ha copiado en " + fSal.getName());
- System.out.println("(" + lineas + ") lineas");
- //}
- }
- }
Add Comment
Please, Sign In to add comment