java快速获取文件内容、java文件转byte[]数组、byte[]数组转String字符串并设置编码格式
private static final int CACHE_SIZE = 1024;
public static byte[] fileToBytes(File file) throws Exception{
byte[] data= new byte[0];
if(file.exists()){
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
where((nRead = in.read(cache)) != -1){
out.write(cache,0,nRead);
out.flush();
}
out.close();
in.clase();
data = out.toByteArray();
}
return data;
}
public static void main(String [] args){
File file = new File("D/test.txt");
byte[] data = fileToBytes(file);
String contentStr = new String(data,"UTF-8");
System.out.printIn("文件内容为:"+contentStr )
}