java实现读取文件的内容返回字节数组
1.代码如下所示:
public class FileUtil {
/**
* 方法功能:读取文件内容返回字节流
* @param String fname
* @return byte[]
* */
public static byte[] readFile(String fname){
InputStream fis = null;
ByteArrayOutputStream baos = null;
try{
baos = new ByteArrayOutputStream();
fis = new FileInputStream(fname);
byte[] ch = new byte[1024];
int readLen = 0;
while ((readLen = fis.read(ch)) != -1) {
baos.write(ch, 0, readLen);
}
return baos.toByteArray();
}catch (Exception e){
e.printStackTrace();
}
finally{
try{
if (fis != null) {
fis.close();
}
}catch (IOException e) {}
try{
if (baos != null) {
baos.close();}
}catch (IOException e) {}
}
return null;
}
public static void main(String[] args) throws UnsupportedEncodingException {
String filename = "E:\\test\\system\\test.txt";//注意修改为自己的文件名
FileUtil fileUtil = new FileUtil();
byte[] fileByte = fileUtil.readFile(filename);
String fileStr = new String(fileByte,"utf-8");//注意字符集写入与读取保持一致。
System.out.println(fileStr);
}
}