关于文件备份的三种方式解答
需要的jar包
jcifs
jcifs
1.3.17
commons-net
commons-net
3.3
commons-io
commons-io
2.5
引入jar包 我的是maven项目 直接在pom.xml文件中添加
方式1:把上传文件备份到本地指定的某一个盘符下
这里我引入了数据库中存在的路径字段Storename 它格式是:doc/日期/文件名称.后缀名
documentService.getList() 查找到的数据库中的数据信息
public void copyFile() {//备份到指定盘符下
List<Document> docs = null;
try {
docs = documentService.getList();
} catch (Exception e1) {
e1.printStackTrace();
}
if(ListUtil.isEmpty(docs)){
break;
}
for(Document d : docs) {
File source = new File(PathUtil.getUploadPath()+File.separatorChar+d.getStorename());//上传的文件所在的路径及文件名称
if(!source.exists()) {
logger.info("文件不存在");
continue;
}
logger.info("源文件路径:"+source);
String path = "D:\\DOC\\";
String st = d.getStorename();
String time = st.substring(4, 12);//字符串截取时间
File remote = new File(path+File.separatorChar+"doc"+File.separatorChar+time+File.separatorChar);
if(!remote.exists()) {//文件夹不存在 即创建
remote.mkdirs();
}
File remoteFile = null;
if(remote.listFiles().length==0) {//该文件夹下没有文件
remoteFile = new File(remote +"/"+ source.getName());
try {
Files.copy(source.toPath(), remoteFile.toPath());
} catch (IOException e) {
String msg = "发生错误:" + e.getLocalizedMessage();
logger.error(msg);
}
}else {
File[] fa = remote.listFiles();
List<String> list = new ArrayList<>();
for(int i = 0; i < fa.length; i++) {
list.add(fa[i].getName());
}
if(list.contains(source.getName())) {
logger.info("存在相同文件,不复制");
}else {
remoteFile = new File(remote+"/"+source.getName());
try {
Files.copy(source.toPath(), remoteFile.toPath());
} catch (IOException e) {
String msg = "发生错误:" + e.getLocalizedMessage();
logger.error(msg);
}
logger.info("没有相同文件,复制");
}
}
}
}
使用自带的Files.copy(source.toPath(), remoteFile.toPath());这个方法 整理备份的运行速度会提高
方式2:备份到服务器的共享目录中
public void shareFile() {//备份到共享文件目录下
List<Document> docs = null;
try {
docs = documentService.getList();
} catch (Exception e1) {
e1.printStackTrace();
}
if(ListUtil.isEmpty(docs)){
break;
}
for(Document d : docs) {
try {
InputStream in = null;
OutputStream out = null;
File localFile = new File(PathUtil.getUploadPath()+File.separatorChar+d.getStorename());//上传的文件所在的路径及文件名称
if(!localFile.exists()) {
logger.info("文件不存在");
continue;
}
logger.info("源文件路径:"+localFile);
String host ="192.168.x.xxx";//远程服务器的地址
String username = "xxx";//用户名
String password = "xxx";//密码
String path = "/share/";//远程服务器共享文件夹名称
String remoteUrl = "smb://" + username + ":" + password + "@" + host + path+ (path.endsWith("/") ? "" : "/");
String st = d.getStorename();
String time = st.substring(4, 12);//字符串截取时间
SmbFile remote = new SmbFile(remoteUrl+"doc"+"/"+time+"/");
if(!remote.exists()) {//文件夹不存在 即创建
remote.mkdirs();
}
SmbFile remoteFile = null;
if(remote.listFiles().length==0) {//该文件夹下没有文件
try {
remoteFile = new SmbFile(remote +"/"+ localFile.getName());
remoteFile.connect();
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[4096];
int len = 0;
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
}catch(Exception e) {
String msg = "发生错误:" + e.getLocalizedMessage();
logger.error(msg);
}finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
}else {
SmbFile[] fa = remote.listFiles();
List<String> list = new ArrayList<>();
for(int i = 0; i < fa.length; i++) {
list.add(fa[i].getName());
}
if(list.contains(localFile.getName())) {
logger.info("存在相同文件,不复制");
}else {
remoteFile = new SmbFile(remote+"/"+localFile.getName());
try {
remoteFile.connect();
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[4096];
int len = 0;
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
}catch(Exception e) {
String msg = "发生错误:" + e.getLocalizedMessage();
logger.error(msg);
}finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
logger.info("没有相同文件,复制");
}
}
}catch(Exception ee){
String msg = "发生错误:" + ee.getLocalizedMessage();
logger.error(msg);
}
}
}
方式三:备份到ftp服务中 (其实就相当于把文件上传到ftp服务器)
public class FtpUtils {
//日志对象
Logger logger = LoggerFactory.getLogger(FtpUtils.class);
public String hostname ="192.168.X.XXX"; //ftp服务器地址
public Integer port = 21;//ftp服务器端口号默认为21
public String username ="XXX";//ftp登录账号
public String password = "XXX";//ftp登录密码
public FTPClient ftpClient = null;
/**
* 初始化ftp服务器
*/
public void initFtpClient() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
logger.info("connecting...ftp服务器:"+this.hostname+":"+this.port);
ftpClient.connect(hostname, port); //连接ftp服务器
ftpClient.login(username, password); //登录ftp服务器
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
if(!FTPReply.isPositiveCompletion(replyCode)){
logger.info("connect failed...ftp服务器:"+this.hostname+":"+this.port);
}
logger.info("connect successfu...ftp服务器:"+this.hostname+":"+this.port);
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 备份文件
* @param pathname ftp服务保存地址
* @param fileName 备份到ftp的文件名
* @param originfilename 需要备份的文件名称(绝对地址) *
* @return
*/
public boolean copyFile( String pathname, String fileName,String originfilename){
boolean flag = false;
InputStream inputStream = null;
try{
inputStream = new FileInputStream(originfilename);
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
logger.info("备份文件成功");
}catch (Exception e) {
e.printStackTrace();
logger.info("备份失败:"+e.toString());
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* 备份文件
* @param pathname ftp服务保存地址
* @param fileName 备份到ftp的文件名
* @param inputStream 输入文件流
* @return
*/
public boolean copyFile( String pathname, String fileName,InputStream inputStream){
boolean flag = false;
try{
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
}catch (Exception e) {
e.printStackTrace();
logger.info("错误信息:"+e.toString());
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}
//改变目录路径
public boolean changeWorkingDirectory(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
logger.info("进入文件夹" + directory + " 成功!");
} else {
logger.info("进入文件夹" + directory + " 失败!开始创建文件夹");
}
} catch (Exception ioe) {
ioe.printStackTrace();
}
return flag;
}
//创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
public boolean CreateDirecroty(String remote) throws Exception {
boolean success = true;
String directory = remote + "/";
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
logger.info("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return success;
}
//判断ftp服务器文件是否存在
public boolean existFile(String path)throws Exception {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
//创建目录
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
if (flag) {
logger.info("创建文件夹" + dir + " 成功!");
} else {
logger.info("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}
public void ftpFile() {//ftp 文件备份
List<Document> docs = null;
while(true){
try {
docs = documentService.getList();
} catch (Exception e1) {
e1.printStackTrace();
}
if(ListUtil.isEmpty(docs)){
break;
}
for(Document d : docs) {
String source = PathUtil.getUploadPath()+File.separatorChar+d.getStorename();
File localFile = new File(PathUtil.getUploadPath()+File.separatorChar+d.getStorename());//上传的文件所在的路径及文件名称
if(!localFile.exists()) {
logger.info("文件不存在");
continue;
}
String st = d.getStorename();
String time = st.substring(4, 12);//字符串截取时间
String path = ConfigLoad.getStringValue("ftp_path");//配置文件中指定的一级目录
String remote =path+"doc"+"/"+time;
FtpUtils ftp =new FtpUtils();
ftp.copyFile(remote, localFile.getName(), source);
}
}
ftp文件的多层目录创建 使用递归的方式