工具類:
public static void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException {
FileOutputStream fs=new FileOutputStream( path + "/"+ filename);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read(buffer))!=-1)
{
bytesum+=byteread;
fs.write(buffer,0,byteread);
fs.flush();
}
fs.close();
stream.close();
}
public static byte[] readFile(File f_file) throws Exception{
InputStream is = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
is = new FileInputStream(f_file);// pathStr 文件路徑
byte[] b = new byte[1024];
int n;
while ((n = is.read(b)) != -1) {
out.write(b, 0, n);
}// end while
} catch (Exception e) {
throw new Exception("System error,SendTimingMms.getBytesFromFile", e);
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
}// end try
}// end if
}// end try
byte[] temp = out.toByteArray();
return temp;
}
調用測試:
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream(new File("D:/asd2019-09-09.xls"));
SaveFileFromInputStream(fileInputStream, "E:/", "asd.txt");
byte[] str = readFile(new File("D:/asd2019-09-09.xls"));
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}