O código a seguir mostra como converter o conteúdo de uma arquivo para uma String.
Não utilize esse código para arquivos demasiadamente grandes, pois provavelmente receberá OutOfMemoryError da JVM.
/**
* Tranforma o arquivo em String
*
* @param file
* Caminho do arquivo que deve sofrer a conversão
*
* @return String representando o conteúdo do arquivo
*/
public static String fileToString(String file) {
String result = null;
DataInputStream in = null;
try {
File f = new File(file);
byte[] buffer = new byte[(int) f.length()];
in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
result = new String(buffer);
} catch (IOException e) {
throw new RuntimeException("IO problem in fileToString", e);
} finally {
try {
in.close();
} catch (IOException e) {
/* ignorar */
}
}
return result;
}
Nenhum comentário:
Postar um comentário