- 从路径A复制到路径B
/**
* 根据文件路径上传文件
* @param path
* @param fileDocment
* @return
*/
private String fileUploadByFilePath(String path, String fileDocment) {
// 读取图片
File fileImage = new File(path);
String filepath = fileDocment + File.separator + fileImage.getName();
FileInputStream fis = null;
try {
fis = new FileInputStream(fileImage);// 建立一个输入流对象
} catch (FileNotFoundException e1) {
log.error("read file error{}", e1);
}
// 写入路径
File fileParent = new File(fileDocment);// 新建文件目录
if (!fileParent.exists()) {// 不存在则创建路径
fileParent.mkdirs();
}
File fileElectronicFence = new File(filepath);
FileOutputStream fos = null;
if (!fileElectronicFence.exists()) {
try {
fileElectronicFence.createNewFile();
fos = new FileOutputStream(filepath);
byte[] buf = new byte[1024];// 每次读入文件数据量
int len = -1;
while ((len = (fis.read(buf))) != -1) {
fos.write(buf);
fos.flush();
}
} catch (IOException e) {
log.error("create file error{}", e);
} finally {
try {
fos.flush();
fos.close();
fis.close();
} catch (IOException e) {
log.error("close OutputStream fail{}", e);
}
}
}
return filepath;
}
- 通过流上传文件
/**
* 描述 : <将文件保存到指定路径>. <br>
*<p>
*
* @param multifile
* @param path 目标路径
* @param fileName 文件名称
* @return
* @throws IOException
*/
public static String saveFileToServer(MultipartFile multifile, String path, String fileName)
throws IOException {
// 创建目录
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
// 读取文件流并保持在指定路径
InputStream inputStream = multifile.getInputStream();
OutputStream outputStream = new FileOutputStream(path
+ fileName);
byte[] buffer = multifile.getBytes();
int bytesum = 0;
int byteread = 0;
while ((byteread = inputStream.read(buffer)) != -1) {
bytesum += byteread;
outputStream.write(buffer, 0, byteread);
outputStream.flush();
}
outputStream.close();
inputStream.close();
return path+ fileName;
} ;