Arquivo txt

7 respostas
abelgomes

Bom dia pessoal, estou querendo fazer a persistencia do arquivo .txt no meu banco de dados!

preciso converter para binario? Como eu faço para salvar esse arquivo?

7 Respostas

fiaux

Escreva os bytes num campo blob.

V

Vc quer gravar ele todo, ou quer quebrar o que tem nele e gravar uma coisa em cada linha ?

abelgomes

sim, no meu banco o campo está como Blob…mas na minha classe como vou fazer para setar esse campo? uma vez que o mapeamento gerado diz que o campo tem que ser um byte[]

e na minha classe File nao tenho o metodo toByteArray()
:s

e agora?

abelgomes

quero gravar o arquivo mesmo “c:\pessoa.txt” o arquivo vai ter que ir pro banco…

T
  1. Determine o tamanho do arquivo (use o método length da classe java.io.File)
  2. Dimensione um array de bytes com esse tamanho
  3. Abra o arquivo (use um FileInputStream) e o leia dentro do array de bytes (use o método read)
  4. Feche o arquivo
  5. Pronto, você tem o arquivo pronto para ser jogado em um blob.
abelgomes

vou testar aqui… :d

valeu ai moçada…

abelgomes
é o seguinte pessoal, consegui fazer oque eu queria..ficou assim
public static byte[] getBytesFromFile(File file) throws IOException {
        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;
    }
Criado 13 de agosto de 2008
Ultima resposta 13 de ago. de 2008
Respostas 7
Participantes 4