Como ler um arquivo de texto contido em um JAR
Dados do artigo
Artigo
Tradução:
Originado de How to read a text file from JAR
Por valderind4
Última alteração feita por hamishwillee
em 08 Dec 2011
Se você deseja ler um arquivo de texto contido em um arquivo JAR(apenas leitura), você deve:
- Incluir o arquivo ".txt" no seu projeto, assim a IDE pode anexá-lo ao pacote JAR.
- Use o seguinte código, para ler o aquivo de texto do arquivo JAR
private String readTextFile(String fileName) throws IOException {
//carrega o arquivo especificado em "fileName"
InputStream input = getClass().getResourceAsStream(fileName);
//Abre fluxos de saída para escrever o conteúdo do arquivo
ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[512];
int bytes;
while ((bytes = input.read (buffer)) > 0) {
output.write (buffer, 0, bytes);
}
input.close ();
//retorna o conteúdo do arquivo lido em String
return new String(output.toByteArray());
}

