您的位置:首页 > 编程语言 > Java开发

java 文件上传 与 把文件解析成一个字节数组简单的后台示例

2016-06-08 16:32 846 查看
工具类:

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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: