|
![]() |
Veremos un programa que hice para intentar copiar archivos con java y tener un cierto contr
La idea es crear una clase que abra una tubería (iostream) para entrada de datos de un archivo, y por supuesto otra para salida, entonces abriremos dos archivos, uno es el original y otro es uno que no existe, que tendrá cero de tamaño y lo iremos llenando con el contenido del original. Como Java permite redimensionar Arrays de forma dinámica podríamos leer en la memoria el contenido entero del archivo y escribirlo entero, pero esto consumiría mucha memoria y no podríamos copiar archivos muy grandes. Una solución sería poner un límite máximo y cuando quede algo por debajo del límite, creamos otro array de datos y lo escribimos, total será menor al máximo... Para hacer algo más ilustrativo, traduje una de mis rutinas hechas en Visual Basic (el cual estoy dejando por completo) para comparar dos archivos y lo hice con pequeños trozos de distintos tamaños hasta llegar a 1 Byte, en Java no es necesario, y la probabilidad de recorrer todos los bloques es bastante difícil...
import java.io.*;
class GusFileCopier{
File FileFrom;
File FileTo;
Object[] FileBufferArray=new Object[20];
boolean dbug=false;
GusFileCopier(String FileFrom, String FileTo){
this(new File(FileFrom),new File(FileTo));
}//end constructor
GusFileCopier(File FileFrom, File FileTo){
this.FileFrom=FileFrom;
this.FileTo=FileTo;
GusInit();
}//end constructor
static void main(String[] args){
GusFileCopier temp=new GusFileCopier(args[0],args[1]);
temp.performCopy();
}//end main
void GusInit(){
for (int i=0;i<FileBufferArray.length;i++){
FileBufferArray[i]=new byte[(int)Math.pow(2,i)];
if(dbug){System.out.println("EXP:"+(Math.pow(2,i)));}
}//end for
}//end gusinit
void performCopy(String FileFrom, String FileTo){
performCopy(new File(FileFrom),new File(FileTo));
}//end copy
void performCopy(File FileFrom, File FileTo){
this.FileFrom=FileFrom;
this.FileTo=FileTo;
performCopy();
}//end copy
void performCopy(CompunautaStackItem FileFrom, CompunautaStackItem FileTo){
performCopy(new File(FileFrom.toString()),new File(FileTo.toString()));
}//end copy
void performCopy(){
boolean e=false;
long LengthTo=0;
long LengthFrom=0;
int writed;
FileInputStream StreamFrom;
FileOutputStream StreamTo;
try{
LengthFrom=FileFrom.length();
StreamFrom=new FileInputStream(FileFrom);StreamFrom.close();
}catch(Exception ex){e=true;}
if (e){return ;}
REQManipulation temp=new REQManipulation(FileTo.toString());
File tmp=new File(temp.urlFromFile(System.getProperty("file.separator")));
if (!tmp.toString().equals("")){e=tmp.mkdirs();e=false;}//override
try{
StreamTo=new FileOutputStream(FileTo);StreamTo.close();
}catch (Exception ex){e=true;}
if (e){return ;}
int whichone=0;
if(dbug){System.out.println("READY:");}
try{
StreamFrom=new FileInputStream(FileFrom);
StreamTo=new FileOutputStream(FileTo);
if(dbug){System.out.println("BeForeWhile:LengthFrom:"+LengthFrom+" LengthTo:"+LengthTo);}
while(LengthFrom>LengthTo){
if(dbug){System.out.println("BeForeCalc:LengthFrom:"+LengthFrom+" LengthTo:"+LengthTo);}
if(dbug){System.out.println("CALC:"+Math.log(LengthFrom-LengthTo)/Math.log(2));}
whichone=(int)(Math.log(LengthFrom-LengthTo)/Math.log(2));
if (whichone>(FileBufferArray.length-1)){whichone=FileBufferArray.length-1;}
if(dbug){System.out.println("AfterCalc:LengthFrom:"+LengthFrom+" LengthTo:"+LengthTo+" whichone:"+whichone);}
writed=StreamFrom.read((byte[])FileBufferArray[whichone]);
LengthTo=LengthTo+writed;
StreamTo.write((byte[])FileBufferArray[whichone],0,writed);
if(dbug){System.out.println("AfterWrite:LengthFrom:"+LengthFrom+" LengthTo:"+LengthTo+" whichone:"+whichone);}
}//end while
}catch (Exception ex){return ;}
}//end performcopy
}//end class
Function CmpFiles(F1 As String, F2 As String) As Boolean //devuelve verdadero si los archivos son iguales Dim KB4F1 As String * 4096 Dim KB4F2 As String * 4096 // Dim KB1F1 As String * 1024 Dim KB1F2 As String * 1024 // Dim B1F1 As String * 128 Dim B1F2 As String * 128 // Dim BF1 As String * 8 Dim BF2 As String * 8 // Dim CF1 As String * 1 Dim CF2 As String * 1 Dim LF1 As Single Dim LF2 As Single Dim t As Single Dim Ok As Boolean Dim I As Single Dim St As Single If Not FileExist(F1) Or Not FileExist(F2) Then CmpFiles = False: Exit Function If FileLen(F1) <> FileLen(F2) Then CmpFiles = False: Exit Function LF1 = FileLen(F1) LF2 = FileLen(F2) // step 4096 Open F1 For Random As #7 Len = 4096 Open F2 For Random As #8 Len = 4096 St = 1 t = Int(LF1 / 4096) For I = St To t Get #7, I, KB4F1 Get #8, I, KB4F2 If KB4F1 <> KB4F2 Then CmpFiles = False: Close #7, #8: Exit Function Next I Close #7, #8 // step 1024 Open F1 For Random As #7 Len = 1024 Open F2 For Random As #8 Len = 1024 St = 4096 * t / 1024 + 1 t = Int(LF1 / 1024) For I = St To t Get #7, I, KB1F1 Get #8, I, KB1F2 If KB1F1 <> KB1F2 Then CmpFiles = False: Close #7, #8: Exit Function Next I Close #7, #8 // step 128 Open F1 For Random As #7 Len = 128 Open F2 For Random As #8 Len = 128 St = 1024 * t / 128 + 1 t = Int(LF1 / 128) For I = St To t Get #7, I, B1F1 Get #8, I, B1F2 If B1F1 <> B1F2 Then CmpFiles = False: Close #7, #8: Exit Function Next I Close #7, #8 // step 8 Open F1 For Random As #7 Len = 8 Open F2 For Random As #8 Len = 8 St = 128 * t / 8 + 1 t = Int(LF1 / 8) For I = St To t Get #7, I, BF1 Get #8, I, BF2 If BF1 <> BF2 Then CmpFiles = False: Close #7, #8: Exit Function Next I Close #7, #8 // step 1 Open F1 For Random As #7 Len = 1 Open F2 For Random As #8 Len = 1 St = 8 * t / 1 + 1 t = Int(LF1 / 1) For I = St To t Get #7, I, CF1 Get #8, I, CF2 If CF1 <> CF2 Then CmpFiles = False: Close #7, #8: Exit Function Next I Close #7, #8 CmpFiles = True: Exit Function End Function
Para compilar este programa sólo hacemos:
javac GusFileCopier.java |
Y para probarlo:
java GusFileCopier archivoorigen archivodestino |
Esto copiará el archivo, es decir creará uno nuevo y lo completará con le que se lea del original.