java简单文件上传
2016-01-28 14:24
363 查看
public static void doUpload(File file,String path, String name) throws Exception {
if(null == file){
throw new Exception();
}
// 基于file创建一个文件输入流
InputStream is = new FileInputStream(file);
// 设置上传文件目录
//String uploadPath = ServletActionContext.getServletContext().getRealPath("/") + path;
File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();
}
// 设置目标文件
File toFile = new File(path, name);
// 创建一个输出流
OutputStream os = new FileOutputStream(toFile);
// 设置缓存
byte[] buffer = new byte[1024];
int length = 0;
try {
// 读取myFile文件输出到toFile文件中
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} catch (IOException e) {
e.getMessage();
} finally {
// 关闭输入流
if (null != is) {
is.close();
}
// 关闭输出流
if (null != os) {
os.close();
}
}
}
if(null == file){
throw new Exception();
}
// 基于file创建一个文件输入流
InputStream is = new FileInputStream(file);
// 设置上传文件目录
//String uploadPath = ServletActionContext.getServletContext().getRealPath("/") + path;
File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();
}
// 设置目标文件
File toFile = new File(path, name);
// 创建一个输出流
OutputStream os = new FileOutputStream(toFile);
// 设置缓存
byte[] buffer = new byte[1024];
int length = 0;
try {
// 读取myFile文件输出到toFile文件中
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} catch (IOException e) {
e.getMessage();
} finally {
// 关闭输入流
if (null != is) {
is.close();
}
// 关闭输出流
if (null != os) {
os.close();
}
}
}
相关文章推荐
- Java实现Runnable接口方式实现多线程的优势
- java中的内部类总结
- Java面向对象个人学习和理解
- java将文件夹下的一个文件拷贝到另一个文件夹下
- java中基础类型的初始值,以及一些平时不注意的小知识
- java 通配符
- Eclipse 官方简体中文语言包下载地址及安装方法
- springsecurity源码查看网址
- The connection to adb is down, and a severe error has occured
- JAVA多态学习3
- eclipse常用命令
- 百度webuploader上传组件学习,Java版
- eclipse中使用maven插件的时候,运行run as maven build的时候报错
- 如何配置jdk和使用
- Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)
- Java强制转化
- Java里接口的相关知识
- Java简易计算器
- Java中的自动装箱与拆箱
- 常见 Java 字节码 指令 助记符