Foro de elhacker.net

Programación => Java => Mensaje iniciado por: ryhuso en 17 Abril 2020, 13:31 pm



Título: Modificar fichero en java
Publicado por: ryhuso en 17 Abril 2020, 13:31 pm
Hola mi problema es que necesito modificar un fichero en java pero no se como hacerlo
busque por la web y no encontre ejemplos claros.

lo que tengo que hacer es que en un fichero que tengo creado de una agenda modificarle el numero de telefono.

Código:
public void altaFactura(Abonado nueva) {
        try {
            File f = new File("facturas_telf.dat");
            FileWriter fw;
            BufferedWriter bw;
            if (f.exists()) {
                fw = new FileWriter(f, true);
                bw = new BufferedWriter(fw);
                bw.newLine();
                bw.write(nueva.numeroAbonado + "%" + nueva.nombre + "%" + nueva.factura);
            } else {
                fw = new FileWriter(f);
                bw = new BufferedWriter(fw);
                bw.write(nueva.numeroAbonado + "%" + nueva.nombre + "%" + nueva.factura);
            }
            bw.close();
            fw.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }


lo que quiero es buscar un numero de telefono numeroAbonado en este caso y cambiar el numero o nombre .... modificarlo .


Título: Re: Modificar fichero en java
Publicado por: rub'n en 17 Abril 2020, 13:35 pm
Hola mi problema es que necesito modificar un fichero en java pero no se como hacerlo
busque por la web y no encontre ejemplos claros.

lo que tengo que hacer es que en un fichero que tengo creado de una agenda modificarle el numero de telefono.

Bueno, y como hiciste el fichero? muestra a ver que tal. parte del código, y se mas descriptivo.

Usa GeSHi si vas a copiar código java.


Título: Re: Modificar fichero en java
Publicado por: @XSStringManolo en 17 Abril 2020, 14:19 pm
Hay muchas formas distinas de hacer lo mismo, según el tipo de archivo, tamaño, permisos, frecuencia de escritura...

Por la info que das...

Supongo que quieres hacer algo así:
Código
  1. String contactos = FileUtils.readFileToString(new File("Contactos.vcf"), "UTF-8");
  2. contactos = contactos.replaceAll("671718181", "653717272");
  3. File contactosM = new File("ContactosModificados.vcf");
  4. FileUtils.writeStringToFile(contactosM, contactos, "UTF-8");


Título: Re: Modificar fichero en java
Publicado por: ryhuso en 17 Abril 2020, 14:23 pm
Bueno, y como hiciste el fichero? muestra a ver que tal. parte del código, y se mas descriptivo.

Usa GeSHi si vas a copiar código java.

[
Código:
 public void altaFactura(Abonado nueva) {
        try {
            File f = new File("facturas_telf.dat");
            FileWriter fw;
            BufferedWriter bw;
            if (f.exists()) {
                fw = new FileWriter(f, true);
                bw = new BufferedWriter(fw);
                bw.newLine();
                bw.write(nueva.numeroAbonado + "%" + nueva.nombre + "%" + nueva.factura);
            } else {
                fw = new FileWriter(f);
                bw = new BufferedWriter(fw);
                bw.write(nueva.numeroAbonado + "%" + nueva.nombre + "%" + nueva.factura);
            }
            bw.close();
            fw.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
]


Título: Re: Modificar fichero en java
Publicado por: rub'n en 17 Abril 2020, 15:16 pm
bien como es el Objeto Abonado ?

También se podría escribir en forma de objeto Serializado.


Título: Re: Modificar fichero en java
Publicado por: ryhuso en 17 Abril 2020, 15:30 pm
el objeto abonado son 3 cadenas
telefono
nombre
factura


Título: Re: Modificar fichero en java
Publicado por: rub'n en 17 Abril 2020, 18:09 pm
el objeto abonado son 3 cadenas
telefono
nombre
factura


  • Para no hardcodear la ruta mejor busca el fichero con un JFileChooser
  • Para reemplazar invoca a reemplazarNumero(), con dos parámetros String viejo y el String nuevo

>:D Si quieres pruebalo.


Ejemplo bean Abonado

Código
  1. /**
  2.  * @implSpec NO-THREAD-SAFE
  3.  */
  4. public class Abonado {
  5.  
  6.    private String nombre;
  7.    private String telefono;
  8.    private String factura;
  9.  
  10.    public String getNombre() {
  11.        return nombre;
  12.    }
  13.  
  14.    public void setNombre(String nombre) {
  15.        this.nombre = nombre;
  16.    }
  17.  
  18.    public String getTelefono() {
  19.        return telefono;
  20.    }
  21.  
  22.    public void setTelefono(String telefono) {
  23.        this.telefono = telefono;
  24.    }
  25.  
  26.    public String getFactura() {
  27.        return factura;
  28.    }
  29.  
  30.    public void setFactura(String factura) {
  31.        this.factura = factura;
  32.    }
  33.  
  34.    @Override
  35.    public String toString() {
  36.        return "Abonado{" +
  37.                "nombre='" + nombre + '\'' +
  38.                ", telefono='" + telefono + '\'' +
  39.                ", factura='" + factura + '\'' +
  40.                '}';
  41.    }
  42. }

Código
  1. import javax.swing.*;
  2. import java.io.*;
  3. import java.nio.file.Files;
  4. import java.nio.file.Path;
  5. import java.util.stream.Collectors;
  6.  
  7. /**
  8.  *
  9.  */
  10. public class FacturasTelf {
  11.  
  12.    private Path rutaFichero;
  13.  
  14.    public FacturasTelf() {
  15.  
  16.        final Abonado abonado = new Abonado();
  17.        abonado.setNombre("gas");
  18.        abonado.setFactura("lus DeboSiempre");
  19.        abonado.setTelefono("3999 999 050");
  20.  
  21.        //Buscar Fichero no hardcoded
  22.        if(buscarFichero()) {
  23.            //Escritura normal objeto
  24.            //this.altaFactura(abonado);
  25.  
  26.            //Invocar para reemplazar viejo numero telefonico Basico
  27.            //Puedes invocarlo por medio de un listerner
  28.            this.reemplazarNumero("3999 111 222" , "3999 111 111");
  29.        }
  30.  
  31.    }
  32.  
  33.    public boolean buscarFichero() {
  34.        final JFileChooser jFileChooser = new JFileChooser();
  35.        jFileChooser.setDialogType(JFileChooser.FILES_ONLY);
  36.        jFileChooser.setDialogTitle("Abrir Fichero");
  37.        final int opc = jFileChooser.showOpenDialog(null);
  38.        boolean value = false;
  39.        if(opc == JFileChooser.OPEN_DIALOG) {
  40.            rutaFichero = jFileChooser.getSelectedFile().toPath();
  41.            value = Boolean.TRUE;
  42.        } else {
  43.            JOptionPane.showMessageDialog(null, "Fichero sin seleccionar");
  44.        }
  45.        return value;
  46.    }
  47.  
  48.  
  49.  
  50.    /**
  51.      *
  52.      * @param nueva
  53.      */
  54.    public void altaFactura(Abonado nueva) {
  55.  
  56.        try (final FileWriter fw = new FileWriter(rutaFichero.toFile(), true);
  57.             final BufferedWriter bw = new BufferedWriter(fw)) {
  58.  
  59.            if (rutaFichero.toFile().exists()) {
  60.                //Para reemplazar numero
  61.  
  62.                bw.newLine();
  63.                bw.write(nueva.getTelefono() + "%" + nueva.getNombre() + "%" + nueva.getFactura());
  64.  
  65.  
  66.            } else { //No ejecuta, new File() lo crea por defecto
  67.                //fw = new FileWriter(f);
  68.                //bw = new BufferedWriter(fw);
  69.  
  70.                bw.write(nueva.getTelefono() + "%" + nueva.getNombre() + "%" + nueva.getFactura());
  71.            }
  72.        } catch (IOException e) {
  73.            System.out.println(e);
  74.        }
  75.    }
  76.  
  77.  
  78.    /**
  79.      * Metodo usado para reemplazar el viejo numero
  80.      *
  81.      * @param viejo
  82.      * @param numeroReemplazar
  83.      */
  84.    public void reemplazarNumero(final String viejo, final String numeroReemplazar) {
  85.  
  86.        final StringBuilder sb = new StringBuilder();
  87.        String nuevaData = "";
  88.  
  89.        try (final BufferedReader reader = new BufferedReader(Files.newBufferedReader(rutaFichero))) {
  90.  
  91.            sb.append( reader
  92.                    .lines()
  93.                    .collect(Collectors.joining( System.lineSeparator() )));
  94.  
  95.            nuevaData = sb.toString().replaceAll(viejo, numeroReemplazar );
  96.  
  97.        } catch(IOException e) {
  98.            //mejor un logger
  99.            e.printStackTrace();
  100.        }
  101.  
  102.        /**
  103.          *  Nuevamente escribimos el fichero
  104.          */
  105.        try (final BufferedWriter writer = new BufferedWriter(Files.newBufferedWriter(rutaFichero))) {
  106.  
  107.            writer.write(nuevaData);
  108.            writer.write(System.lineSeparator()); //separador del sistema
  109.            JOptionPane.showMessageDialog(null, "Reemplazo listo");
  110.  
  111.        } catch(IOException e) {
  112.            //mejor un logger
  113.            e.printStackTrace();
  114.        }
  115.  
  116.    }
  117.  
  118.    public static void main(String ...blablla) {
  119.        new FacturasTelf();
  120.    }
  121. }



Aunque prefiero los DSL por ejemplo algo simple

Código
  1.        final Abonado abonado = new Abonado();
  2.        abonado.setNombre("Factura Telefono N#2144141");
  3.        abonado.setFactura("lus DeboSiempre");
  4.        abonado.setTelefono("3999 999 050");
  5.  
  6.  
  7.         /**
  8.          * Para escribir en un fichero ejemplo
  9.          */
  10.       new IFacturar.FacturaImpl()
  11.               .buscarFichero()
  12.               .escribirFichero(abonado) //toString()
  13.               .make();
  14.  
  15.        /**
  16.          * Para reemplazar String en un fichero, no tan eficiente, mejor RandomAccessFile
  17.          */
  18.        new IFacturar.FacturaImpl()
  19.                .guardarFichero()
  20.                .reemplazar(e -> e.replaceAll("3999 999 050", "3999 000 000"))//con expresión lambda de una vez.
  21.                .make();

Código
  1. package foro;
  2.  
  3. import javax.swing.*;
  4. import java.io.*;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.nio.file.StandardOpenOption;
  8. import java.util.Objects;
  9. import java.util.function.UnaryOperator;
  10. import java.util.logging.Logger;
  11.  
  12. /**
  13.  * DSL simple.
  14.  */
  15. public interface IFacturar {
  16.  
  17.    /**
  18.      * @param <T>
  19.      */
  20.    interface Builder<T> {
  21.  
  22.        default Builder<T> buscarFichero() {
  23.            return this;
  24.        }
  25.  
  26.        default Builder<T> guardarFichero() {
  27.            return this;
  28.        }
  29.  
  30.        Builder<T> altaFactura(Abonado nueva);
  31.  
  32.        Builder<T> reemplazar(final UnaryOperator<String> unaryOperator);
  33.  
  34.        <T> Builder<T> escribirFichero(final T t);
  35.  
  36.        T make();
  37.  
  38.    }
  39.  
  40.    @SuppressWarnings("unchecked")
  41.    abstract class AbstractBaseClassFactura<S> implements Builder<S> {
  42.  
  43.        private Path rutaFichero;
  44.        private String nuevaData = "";
  45.        private static final Logger LOG = Logger.getLogger(AbstractBaseClassFactura.class.getSimpleName());
  46.  
  47.        public AbstractBaseClassFactura() {
  48.  
  49.        }
  50.  
  51.        @Override
  52.        public Builder<S> buscarFichero() {
  53.            jFileChooserBuscar();
  54.            return this;
  55.        }
  56.  
  57.        private void jFileChooserBuscar() {
  58.            final JFileChooser jFileChooser = new JFileChooser();
  59.            jFileChooser.setDialogType(JFileChooser.FILES_ONLY);
  60.            jFileChooser.setDialogTitle("Abrir Fichero");
  61.            final int opc = jFileChooser.showOpenDialog(null);
  62.            if (opc == JFileChooser.OPEN_DIALOG) {
  63.                this.rutaFichero = jFileChooser.getSelectedFile().toPath();
  64.            }
  65.        }
  66.  
  67.        @Override
  68.        public Builder<S> guardarFichero() {
  69.            jFileChooserGuardar();
  70.            return this;
  71.        }
  72.  
  73.        private void jFileChooserGuardar() {
  74.            final JFileChooser jFileChooser = new JFileChooser();
  75.            jFileChooser.setDialogType(JFileChooser.DIRECTORIES_ONLY);
  76.            jFileChooser.setDialogTitle("Guardar Fichero");
  77.            final int opc = jFileChooser.showSaveDialog(null);
  78.            if (opc == JFileChooser.APPROVE_OPTION) {
  79.                this.rutaFichero = jFileChooser.getSelectedFile().toPath();
  80.            }
  81.        }
  82.  
  83.        /**
  84.          * @param nueva
  85.          */
  86.        public Builder<S> altaFactura(Abonado nueva) {
  87.            try (final FileWriter fw = new FileWriter(rutaFichero.toFile(), true);
  88.                 final BufferedWriter bw = new BufferedWriter(fw)) {
  89.  
  90.                if (rutaFichero.toFile().exists()) {
  91.                    bw.newLine();
  92.                    bw.write(nueva.getTelefono() + "%" + nueva.getNombre() + "%" + nueva.getFactura());
  93.                    JOptionPane.showMessageDialog(null, "Fichero escrito correctamente!");
  94.  
  95.                }
  96.            } catch (IOException e) {
  97.                LOG.warning(e.getMessage());
  98.            }
  99.            return this;
  100.        }
  101.  
  102.        /**
  103.          * Con UnaryOperator para reemplazar el numero por medio de expresion lambda
  104.          *
  105.          * @param unaryOperator
  106.          * @return Builder<S>
  107.          */
  108.        public Builder<S> reemplazar(final UnaryOperator<String> unaryOperator) {
  109.            Objects.requireNonNull(rutaFichero, () -> "ruta destino es nula");
  110.            Path destino = rutaFichero;
  111.            final long id = System.currentTimeMillis();
  112.            //tomar extension
  113.            final String ext = destino.getFileName().toString().substring(destino.getFileName().toString().lastIndexOf("."));
  114.            final String fileName = destino.getFileName().toString().replace(ext, id +"reemplazado"+ ext);
  115.            destino = destino.resolveSibling(fileName);
  116.  
  117.            try (final BufferedReader reader = new BufferedReader(Files.newBufferedReader(rutaFichero));
  118.                 final BufferedWriter wr = new BufferedWriter(Files.newBufferedWriter(destino, StandardOpenOption.CREATE))) {
  119.                reader.lines()
  120.                        .map(unaryOperator)
  121.                        .forEach(e -> {
  122.                            try {
  123.                                wr.write(e);
  124.                                wr.write(System.lineSeparator());
  125.                            } catch (IOException ex) {
  126.                                ex.printStackTrace();
  127.                            }
  128.                        });
  129.                JOptionPane.showMessageDialog(null, "Reemplazo listo!");
  130.            } catch (IOException e) {
  131.                LOG.warning(e.getMessage());
  132.            }
  133.            return this;
  134.        }
  135.  
  136.        /**
  137.          * Escritura de fichero
  138.          */
  139.        @SuppressWarnings("unchecked")
  140.        public <O> Builder<O> escribirFichero(O abonado) {
  141.            Objects.requireNonNull(rutaFichero,"ruta de fichero es nula");
  142.            try (final BufferedWriter writer = new BufferedWriter(Files.newBufferedWriter(rutaFichero))) {
  143.  
  144.                writer.write(abonado.toString());
  145.                writer.write(System.lineSeparator()); //separador del sistema
  146.                JOptionPane.showMessageDialog(null, "Escritura Lista!");
  147.  
  148.            } catch (IOException e) {
  149.                LOG.warning(e.getMessage());
  150.            }
  151.            return (Builder<O>) this;
  152.        }
  153.    }
  154.  
  155.    /**
  156.      *
  157.      */
  158.    class FacturaImpl extends AbstractBaseClassFactura<FacturaImpl> {
  159.  
  160.        @Override
  161.        public FacturaImpl make() {
  162.            return new FacturaImpl();
  163.        }
  164.  
  165.    }
  166.  
  167.    public static void main(String... blablla) {
  168.  
  169.        final Abonado abonado = new Abonado();
  170.        abonado.setNombre("Factura Telefono N#2144141");
  171.        abonado.setFactura("lus DeboSiempre");
  172.        abonado.setTelefono("3999 999 050");
  173.  
  174.        /**
  175.          * Para escribir en un fichero ejemplo
  176.          */
  177.       /*new IFacturar.FacturaImpl()
  178.                .buscarFichero()
  179.                .escribirFichero(abonado) //toString()
  180.                .make();*/
  181.  
  182.        /**
  183.          * Para reemplazar String en un fichero, no tan eficiente, mejor RandomAccessFile
  184.          */
  185.        new IFacturar.FacturaImpl()
  186.                .guardarFichero()
  187.                .reemplazar(e -> e.replaceAll("3999 999 050", "3999 000 000"))//con expresión lambda de una vez.
  188.                .make();
  189.  
  190.  
  191.    }
  192. }
  193.  



Título: Re: Modificar fichero en java
Publicado por: ryhuso en 7 Mayo 2020, 15:28 pm
Gracias por la ayuda.. :laugh: