远程->本地->远程
- 下载远程文件,逐行修改符合条件的行内容,将修改完的文件重新上传到指定远程目录下
主要注意访问的url格式为:
smb://账号user:密码password@访问的ip/要访问的文件路径/文件.txt
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class UpdateShareFileDataUtil {
private static String TARGET_URL = "smb://***:***@***/share/java";
@SuppressWarnings("unused")
public static void smbFile(String filePath, HashMap<String, String> paramMap) {
String remotePath = filePath.replace("\\", "/").substring(2);
String remoteUrl = "smb://user:password@" + remotePath;
String localDir = "E:\\tmp";
File file = new File(localDir);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
smbGet(remoteUrl, localDir);
String fileName = localDir + "\\" + filePath.substring(filePath.lastIndexOf("\\") + 1);
updateFile(fileName, paramMap);
}
private static void smbGet(String remoteUrl, String localDir) {
InputStream in = null;
OutputStream out = null;
try {
SmbFile remoteFile = new SmbFile(remoteUrl);
if (remoteFile == null) {
log.info("共享文件不存在");
return;
}
String fileName = remoteFile.getName();
File localFile = new File(localDir + File.separator + fileName);
in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
out = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {
out.write(buffer);
buffer = new byte[1024];
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void updateFile(String localUrl, HashMap<String, String> paramMap) {
try {
String regex = "^#[0-9]=";
Pattern pattern = Pattern.compile(regex);
File file = new File(localUrl);
List<String> list = FileUtils.readLines(file,"UTF-8");
for (int i = 0; i < list.size(); i++){
String lineValue = list.get(i);
Matcher marcher = pattern.matcher(lineValue);
if (marcher.find()){
String param = lineValue.substring(0, lineValue.lastIndexOf("="));
if (paramMap.containsKey(param)) {
String newValue = param + "=" + paramMap.get(param) + ";";
list.remove(i);
list.add(i,newValue);
}
}
}
FileUtils.writeLines(file, "UTF-8", list, false);
} catch (IOException e) {
log.info("更改参数值失败");
}
smbPut(TARGET_URL, localUrl);
}
private static void updateFileName(String localUrl,String newName){
File file = new File(localUrl);
String fileName = file.getAbsolutePath();
fileName = fileName.substring(0,fileName.lastIndexOf(MdcsConstants.STR.BACK_SLASH)+1);
file.renameTo(new File(fileName + newName + ".nc"));
}
private void checkFileExists(String smbUrl,String fileName){
try {
SmbFile smbFile = new SmbFile(smbUrl);
if (smbFile.exists() && smbFile.isFile()){
smbFile.renameTo(new SmbFile(smbUrl.substring(0,smbUrl.lastIndexOf(MdcsConstants.STR.SLASH)+1)+fileName+MdcsConstants.STR.UNDERSCORE+System.currentTimeMillis()+".nc"));
}
} catch (Exception e) {
log.info("文件修改名称失败");
}
}
private static void smbPut(String remoteUrl, String localFilePath) {
InputStream in = null;
OutputStream out = null;
try {
File localFile = new File(localFilePath);
String fileName = localFile.getName();
SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName);
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {
out.write(buffer);
buffer = new byte[1024];
}
} catch (Exception e) {
log.info("文件上传失败");
} finally {
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<>(8);
map.put("#1","22222.");
map.put("#3","44444");
String filePath = "\\\\ip\\【Java从入门到入坟】.nc";
smbFile(filePath,map);
}
}
远程->远程
- 上面的代码是将共享文件下载到本地再进行修改操作,但是当项目发布时,这里的【本地】其实已经不一样了,不能再用类似本地主机时的操作,所以这里改成了直接将远程模板文件直接复制一份在远程临时目录下,直接修改,减少了一步从本地上传到远程的操作
- 这里有个地方不太一样,本地Windows环境下,读取文件内容时可以用
FileUtils.readLines(file,"UTF-8")
获取文件的每一行数据,但是当用 SMB 操作远程文件时,并没有提供相关api,所以改用文件流,具体看代码中的使用
- 此次修改抽取了大部分参数为外部传入
import com.jidian.mdcs.MdcsConstants;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import java.io.*;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class UpdateShareFileDataUtil {
@SuppressWarnings("unused")
public static void smbFile(String filePath, Map<String, String> paramMap, String targetUrl, String punchCodeName,String authMessage,String fileType,String updateRegex) {
log.info("命中模板文件{}",filePath);
String remotePath = filePath.replace(MdcsConstants.STR.BACK_SLASH, MdcsConstants.STR.SLASH).substring(2);
String remoteUrl = authMessage + remotePath;
SmbFile fileResult;
try {
fileResult = new SmbFile(targetUrl);
if (!fileResult.exists() && !fileResult.isDirectory()) {
fileResult.mkdirs();
}
} catch (Exception e) {
log.error("创建目标目录失败",e);
}
smbGet(remoteUrl, targetUrl);
String fileName = targetUrl + MdcsConstants.STR.SLASH + filePath.substring(filePath.lastIndexOf(MdcsConstants.STR.BACK_SLASH) + 1);
updateFile(fileName, paramMap,punchCodeName,fileType,updateRegex);
}
private static void smbGet(String remoteUrl, String localDir) {
log.info("开始下载远程模板文件{}",remoteUrl);
try {
SmbFile remoteFile = new SmbFile(remoteUrl);
if (ObjectUtils.isEmpty(remoteFile)) {
log.error("共享文件{}不存在",remoteUrl);
return;
}
String fileName = remoteFile.getName();
SmbFile localFile = new SmbFile(localDir + MdcsConstants.STR.SLASH + fileName);
try(InputStream in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
OutputStream out = new BufferedOutputStream(new SmbFileOutputStream(localFile))
){
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {
out.write(buffer);
buffer = new byte[1024];
}
}
} catch (Exception e) {
log.error("文件获取失败",e);
}
}
private static void updateFile(String localUrl, Map<String, String> paramMap,String punchCodeName,String fileType,String updateRegex) {
log.info("更新模板文件{}",localUrl);
try {
Pattern pattern = Pattern.compile(updateRegex);
String mpr = "mpr";
if (fileType.equals(mpr) ){
BufferedReader check = new BufferedReader(new InputStreamReader(new SmbFile(localUrl).getInputStream()));
updateCncMap(paramMap,check);
check.close();
}
List<String> list = new ArrayList<>();
String content = "";
StringBuilder stringBuilder = new StringBuilder(content);
try(BufferedReader br = new BufferedReader(new InputStreamReader(new SmbFile(localUrl).getInputStream(),"gbk"))){
String line;
while ((line = br.readLine()) != null) {
Matcher marcher = pattern.matcher(line);
if (marcher.find()){
String param = line.substring(0, line.lastIndexOf(MdcsConstants.STR.EQUALS));
if (paramMap.containsKey(param)) {
String newValue = fileType.equals(mpr) ? param + MdcsConstants.STR.EQUALS + paramMap.get(param) :
param + MdcsConstants.STR.EQUALS + paramMap.get(param) + ";";
list.add(newValue);
}else {
list.add(line);
}
}else {
list.add(line);
}
}
}
list.stream().forEach(item-> stringBuilder.append(item).append("\n"));
OutputStream outputStream = new SmbFile(localUrl).getOutputStream();
outputStream.write(stringBuilder.toString().getBytes());
outputStream.close();
} catch (IOException e) {
log.error("更改参数值失败",e);
}
try {
updateFileName(localUrl,punchCodeName,fileType);
} catch (MalformedURLException e) {
log.error("url路径异常",e);
}
}
private static void updateFileName(String localUrl,String newName,String fileType) throws MalformedURLException {
log.info("开始更新文件 {} 名称为 {}",localUrl,newName);
SmbFile file = new SmbFile(localUrl);
String fileName = localUrl.substring(0,localUrl.lastIndexOf(MdcsConstants.STR.SLASH)+1);
try {
file.renameTo(new SmbFile(fileName + newName + MdcsConstants.STR.DOT+fileType));
} catch (SmbException e) {
log.error("更改文件名失败{}->{}",localUrl,newName,e);
}
}
public static void backupFile(String backupUrl, String fileType){
log.info("开始备份旧数据,目录{}",backupUrl);
String targetUrl = backupUrl + MdcsConstants.STR.SLASH;
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
List<String> backupFileName = new ArrayList<>();
try {
SmbFile file = new SmbFile(targetUrl);
if (file.exists() && file.isDirectory()){
SmbFile[] result = file.listFiles();
log.info("筛选未备份过的数据...");
for (int i=0; i<result.length; i++){
SmbFile fs = result[i];
if (!fs.getName().contains(MdcsConstants.STR.LEFT_SQ_BRACKET)){
backupFileName.add(fs.getName());
}
}
log.info("开始备份");
for (String fileName:backupFileName){
String timeLeft = MdcsConstants.STR.UNDERSCORE + MdcsConstants.STR.LEFT_SQ_BRACKET;
String timeRight = MdcsConstants.STR.RIGHT_SQ_BRACKET + MdcsConstants.STR.DOT;
String backupName = targetUrl + fileName.substring(0,fileName.lastIndexOf(MdcsConstants.STR.DOT))
+timeLeft+df.format(new Date())+timeRight+fileType;
SmbFile smbFile = new SmbFile(targetUrl + fileName);
smbFile.renameTo(new SmbFile(backupName));
}
}
} catch (Exception e) {
log.error("文件目录不存在",e);
}
}
private static Map<String,String> updateCncMap(Map<String,String> paramMap, BufferedReader br){
Map<String,Integer> lbdExists = new HashMap<>(8);
lbdExists.put("l",0);
lbdExists.put("b",0);
lbdExists.put("d",0);
String regexL = "^(?=l=)";
String regexB = "^(?=b=)";
String regexD = "^(?=d=)";
Pattern patternL = Pattern.compile(regexL);
Pattern patternB = Pattern.compile(regexB);
Pattern patternD = Pattern.compile(regexD);
try {
String line = "";
while ((line = br.readLine()) != null){
Matcher marcherL = patternL.matcher(line);
Matcher marcherB = patternB.matcher(line);
Matcher marcherD = patternD.matcher(line);
if (marcherL.find()){
lbdExists.put("l",1);
}else if (marcherB.find()){
lbdExists.put("b",1);
}else if (marcherD.find()){
lbdExists.put("d",1);
}
}
} catch (IOException e) {
log.error("获取文件内容失败",e);
}
String l = "l";
String b = "b";
String d = "d";
if (lbdExists.get(l) == 0){
paramMap.remove("l");
paramMap.remove("_BSX");
paramMap.remove("_RX");
}else if (lbdExists.get(b) == 0){
paramMap.remove("b");
paramMap.remove("_BSY");
paramMap.remove("_RY");
}else if (lbdExists.get(d) == 0){
paramMap.remove("d");
paramMap.remove("_BSZ");
}
return paramMap;
}
private UpdateShareFileDataUtil(){}
}