Ficheiros binarios

3 respostas
andreia_19

kal o codigo pa ler ficheiros binarios??

3 Respostas

T

O código a seguir lê um ficheiro (arquivo, em português do Brasil) binário, mas não faz nada com ele. O código está incompleto de propósito (não tem tratamento de exceções.)

import java.io.*;

....

FileInputStream fis = new FileInputStream ("teste.bin");
byte[] buffer = new byte[10240];
int nBytes;
while ((nBytes = fis.read (buffer)) &gt 0) {
 ... fazer algo com os nBytes lidos dentro do buffer
}
fis.close();
ViniGodoy

Experimente também pesquisar sobre as classes FileChannel e ByteBuffer.

try {
        // Obtain a channel
        ReadableByteChannel channel = new FileInputStream("infile").getChannel();
    
        // Create a direct ByteBuffer; see also e158 Creating a ByteBuffer
        ByteBuffer buf = ByteBuffer.allocateDirect(10);
    
        int numRead = 0;
        while (numRead &gt= 0) {
            // read() places read bytes at the buffer's position so the
            // position should always be properly set before calling read()
            // This method sets the position to 0
            buf.rewind();
    
            // Read bytes from the channel
            numRead = channel.read(buf);
    
            // The read() method also moves the position so in order to
            // read the new bytes, the buffer's position must be set back to 0
            buf.rewind();
    
            // Read bytes from ByteBuffer; see also
            // e159 Getting Bytes from a ByteBuffer
            for (int i=0; i<numRead; i++) {
                byte b = buf.get();
            }
        }
    } catch (Exception e) {
    }

Um link ótimos para códigos de exemplo é:
http://www.exampledepot.com/egs/index.html

Eu tirei esse exemplo daqui:
http://www.exampledepot.com/egs/java.nio/ReadChannel.html
>

andreia_19

bigadao!!! **

Criado 19 de dezembro de 2006
Ultima resposta 20 de dez. de 2006
Respostas 3
Participantes 3