Ajuda em transformar um file em array de bytes

8 respostas
F

Pessoal, bom dia.

Estou com um problema meio simples, mas não estou conseguindo resolver.
Preciso transformar um arquivo (File) em um array de bytes (byte[]).
Alguém pode me ajudar?

private byte[] getBytesFromFile(File file) {
	try {
             //Código para transformação...
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}catch (IOException e) {
		e.printStackTrace();
	}		
	return null;
}

Muito obrigado.

8 Respostas

T
private static final int MAXLENGTH = 100000000; // se for > 100 M então vamos evitar carregar tudo!

private byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = null;
    try {
        long length = file.length();
        if (length > MAXLENGTH) throw new IllegalArgumentException ("File is too big");
        byte[] ret = new byte [(int) length];
        is = new FileInputStream (file);
        is.read (ret);
    } finally {
        if (is != null) try { is.close(); } catch (IOException ex) {}
    }
    return ret;
}
J

Espero que ajude:

private byte[] recuperaFileEmByte(File inFile) { InputStream is = null; byte[] buffer = null; try { is = new FileInputStream(inFile); buffer = new byte[is.available()]; is.read(buffer); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; }

beijosmeliga =*

F

Thingol, muito obrigado pela ajuda, mas o meu array de bytes continua retornando vazio.
Estou postando meu código abaixo, o que estou fazendo de errado?

public byte[] gerarRelatorioTXTParaWeb(java.sql.ResultSet rs, java.util.Map parametros, String relatorio) throws Exception{
		ResultSetFormat rsFormat = new ResultSetFormat(rs);
		File file = new File(relatorio+".txt");
		FileWriter fw = new FileWriter(file);
		fw.write(getCabecalho(parametros)+"\n");
		fw.write(rsFormat.getColunasFormatadas()+"\n");
		String linha;
			while((linha = rsFormat.getNextLinhaOfRsFormatada()) != null){
				fw.write(linha+"\n");
			}		
		return getBytesFromFile(file); 
	}
	
	private byte[] getBytesFromFile(File file) throws IOException {  
		InputStream is = null;
		byte[] ret;
		  try {  
		     long length = file.length();  
		     if (length > MAXLENGTH) throw new IllegalArgumentException ("Arquivo muito grande!");  
		         ret = new byte [(int) length];  
		         is = new FileInputStream (file);  
		         is.read (ret);
		     } finally {  
		         if (is != null) try { is.close(); } catch (IOException ex) {}  
		     }  
		     return ret;
	}

Muito obrigado pela ajuda cara.

T
FileWriter fw = new FileWriter(file);  
     fw.write(getCabecalho(parametros)+"\n");  
     fw.write(rsFormat.getColunasFormatadas()+"\n");  
     String linha;  
         while((linha = rsFormat.getNextLinhaOfRsFormatada()) != null){  
             fw.write(linha+"\n");  
         }

Você precisa fechar um arquivo antes de lê-lo. No seu caso, basta usar:

fw.close();
J

apenas vem vazio? ja verificou no console do seu ide se aparece algum erro?
se aparecer mostra ai para nós…
abração

F

Muito obrigado Thingol.
Valeu a ajuda.
Problema resolvido.

T

No seu caso em particular, eu substituiria seu código por:

public byte[] gerarRelatorioTXTParaWeb (ResultSet rs, Map parametros) throws SQLException, IOException, ... (outras exceptions) ... {
	    ResultSetFormat rsFormat = new ResultSetFormat(rs);   
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter (sw);
		pw.println (getCabecalho (parametros));
		pw.println (rsFormat.getColunasFormatadas());
		for (String linha = rsFormat.getNextLinhaOfRsFormatada(); linha != null; linha = rsFormat.getNextLinhaOfRsFormatada()) {
		    pw.println (linha);
		}
		return sw.toString().getBytes(... ponha o encoding desejado ...);
	}

Isso se você não precisar criar o tal arquivo.

F

Valeu Thingol.
Caramba, ficou bacana.

Criado 5 de junho de 2009
Ultima resposta 5 de jun. de 2009
Respostas 8
Participantes 3