How not to copy the content that already exists in a file?

1

I have asked this question in order to help with this topic:

I am trying to create a copying process, but not complete, that is, only update the contents of one file with the changes made in another.

  • I explain:

I have created two txt files, one with the name A and another with the name B, both files have the same data, until my program alters the data in file A, making changes in the writing (Not deleting the content and writing another but only adding more content), and once these changes are made I want to update or add only the changes that were made not all the content again, just copy what you do not have or lack.

My current code:

My code was very useful when it was time to copy the input data to a file, doing the conversion of InputStream to File, unfortunately it does not perform this operation that I need

My code:

    public boolean creaArchivo2(String ruta, InputStream is)
        throws IOException {

        final int CHUNK_SIZE = 1024 * 4;
        OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(ruta)));
        byte[] chunk = new byte[CHUNK_SIZE];
        int bytesLeidos = 0;

        while ( (bytesLeidos = is.read(chunk)) > 0) {

            os.write(chunk, 0, bytesLeidos);
        }
        os.close();

        boolean verdadero=true;
        return verdadero;

    }

If you know how to achieve it, please let me know Thank you.

    
asked by Abraham.P 21.01.2017 в 23:40
source

1 answer

1

If you only add content to the files, you can do the following:

After adding the content to file A, you get the size size of file B:

File archivoB = new File(ruta);
long length = (File) archivoB.length();

Then create a FileInputStream of file A, and look for the position of the aggregated data, using fis.skip (length) , and you pass it to your modified method, passing true for append (this will open file B to add the data at the end of the file, as documented in the Java API ):

public boolean creaArchivo2(String ruta, InputStream is, boolean append)
    throws IOException {

    final int CHUNK_SIZE = 1024 * 4;
    OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(ruta, append)));
    byte[] chunk = new byte[CHUNK_SIZE];
    int bytesLeidos = 0;

    while ( (bytesLeidos = is.read(chunk)) > 0) {

        os.write(chunk, 0, bytesLeidos);
    }
    os.close();
    return true;

} 
    
answered by 22.01.2017 / 02:11
source