Exceção: ExecutionException

0 respostas
d34d_d3v1l

Boa noite…

Pesquisei aqui no forum e vi um tópico ensinando transformar arquivo para array de bytes…

Ai peguei o algoritmo e criei uma thread que implementa callalbe…

vejam:

public class TransformarFileBytes implements Callable {
    File file;
    
    public TransformarFileBytes(File arquivo){
        this.file = arquivo;
    }
    
    public Object call() throws Exception {
        // Returns the contents of the file in a byte array.
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;

    }
    
}

Usando uma thread separada:

FutureTask<Object> threadAuxiliar = new FutureTask<Object>(new TransformarFileBytes(arq));
            Thread t1 = new Thread(threadAuxiliar);
            t1.start();
            try {
                byte[] bytes = (byte[]) threadAuxiliar.get();
                JOptionPane.showMessageDialog(null, "Parabens! O tamanho do array de bytes ficou em: "+bytes.length,"Sucess!",JOptionPane.INFORMATION_MESSAGE);
            } catch (InterruptedException e1) {
                System.out.println("Exceção: InterruptedException\n" + e1.getMessage());
            } catch (ExecutionException e2) {
                System.out.println("Exceção: ExecutionException\n" + e2.getMessage());
            }

Lancou a excessão que falei no tópico …

Isso foi com um arquivo de 200MB… E o espaço que o Integer disponibiliza pra transformar bem mais que isso né ?
Existe algo que eu possa fazer para evitar essa excessão?
Algum algoritmo mais eficaz pra transfarmar o arquivo em byte[] ?

abraços

Criado 9 de maio de 2011
Respostas 0
Participantes 1