这个适合比较小的文件内容获取,我用的是字节流,不会出现转码问题。
/**
* 根据文件路径获取到文件的内容
*
* @param path
* @return
*/
private String getFileTextByFilePath(String path) {
FileInputStream in = null;
String fileText = null;
try {
//建立连接
in = new FileInputStream(path);
//创建byte[]数组,500000大概400多kb大小这个数组决定可以读取到的文件大小,所以尽量大一点
byte[] buffers = new byte[500000];
int rlength = in.read(buffers, 0, 500000);
//传输的实际byte[]二进制报文流
byte[] file_byte = new byte[rlength];
for (int i = 0; i < file_byte.length; i++) {
file_byte[i] = buffers[i];
}
fileText = new String(file_byte);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileText;
}
本文介绍了一种使用字节流读取小文件内容的方法,避免了转码问题,适用于不超过400多KB的小文件。通过创建FileInputStream实例并指定文件路径,将文件内容读取到byte数组中,然后转换为字符串。
4835

被折叠的 条评论
为什么被折叠?



