應用場景:鑒于某些硬件設備的通信協(xié)議較為復雜,而其功能又依托底層文件實現(xiàn)。考慮直接修改其底層文件的方式來實現(xiàn)業(yè)務(安全性將再從網(wǎng)絡與框架層面考慮)。
一、將需要修改的文件地址發(fā)布為FTP站點
1.開啟Windows功能

FTP服務器.png

TFTP客戶端.png
2.通過ISS創(chuàng)建FTP站點

新建站點.png

連接方式.png

驗證.png
3.創(chuàng)建用戶

創(chuàng)建用戶.png
二、Java代碼實現(xiàn)
1.maven
<!-- FTP 協(xié)議-->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2.常用方法
package com.enjoyor.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FTP協(xié)議工具類
* @author LuoJiaLei
*
*/
public class FTPUtil {
/**
* ftp登錄驗證
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:12
* @version V1.0
* @param ftpIP ftp站點 IP地址
* @param ftpPort ftp站點 端口
* @param ftpUserName ftp站點 登錄用戶名
* @param ftpPassword ftp站點 密碼
* @return FTPClient ftp客戶端連接信息
*/
public static synchronized FTPClient FTPConnect(String ftpIP, int ftpPort,String ftpUserName, String ftpPassword) {
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");// 解決上傳文件時文件名亂碼
int reply = 0;
try {
// 連接至服務器
ftpClient.connect(ftpIP, ftpPort);
// 登錄服務器
ftpClient.login(ftpUserName, ftpPassword);
// 登陸成功,返回碼是230
reply = ftpClient.getReplyCode();
// 判斷返回碼是否合法
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.out.println("未連接到FTP,用戶名或密碼錯誤。");
ftpClient = null;
} else {
System.out.println("FTP連接成功。");
}
} catch (SocketException e) {
ftpClient = null;
System.out.println("FTP的端口錯誤,請正確配置。");
e.printStackTrace();
} catch (IOException e) {
ftpClient = null;
System.out.println("FTP的IP地址可能錯誤,請正確配置。");
e.printStackTrace();
}
return ftpClient;
}
/**
* 判斷服務器路徑是否存在
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:34
* @version V1.0
* @param path 路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static boolean FTPExistPath(String filePath, FTPClient ftpClient) {
boolean flag = false;
FTPFile[] ftpFileArr;
try {
//設置被動模式 linux環(huán)境下listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
ftpFileArr = ftpClient.listFiles(filePath);
if (ftpFileArr.length > 0) {
flag = true;
System.out.println("文件存在");
} else {
System.out.println("文件不存在");
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 判斷服務器文件是否存在
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:34
* @version V1.0
* @param path 路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static boolean FTPExistFile(String filePath,String fileName, FTPClient ftpClient) {
boolean flag = false;
try {
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(filePath);
// 檢驗文件是否存在
InputStream is = ftpClient.retrieveFileStream(fileName);
if(is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE){
return false;
}
if(is != null){
is.close();
ftpClient.completePendingCommand();
}
return true;
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 刪除ftp文件
* @author LuoJiaLei
* @date 2019年2月13日 下午3:50:33
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPDeleteFile(String filePath,String fileName, FTPClient ftpClient) {
boolean flag = false;
try {
System.out.println("開始刪除文件");
// 切換FTP目錄
//設置被動模式 linux環(huán)境listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(filePath);
ftpClient.dele(fileName);
/*ftpClient.logout();*/
flag = true;
System.out.println("刪除文件成功");
} catch (Exception e) {
System.out.println("刪除文件失敗");
e.printStackTrace();
}
return flag;
}
/**
* 下載ftp文件到本地
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:12
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param localPath 本地路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPDownload(String filePath,String fileName, String localPath, FTPClient ftpClient) {
boolean flag = false;
try {
//設置被動模式 linux環(huán)境listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
// 轉(zhuǎn)移到FTP服務器目錄至指定的目錄下
ftpClient.changeWorkingDirectory(filePath);
// 獲取文件列表
FTPFile[] fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(), is);
is.close();
}
}
/*ftpClient.logout();*/
flag = true;
System.out.println("下載文件:" + fileName + " 成功");
} catch (IOException e) {
System.out.println("下載文件:" + fileName + " 失敗");
e.printStackTrace();
}
return flag;
}
/**
* 本地上傳文件到ftp
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:23
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param localPath 本地路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPUpload(String filePath,String fileName, String localPath, FTPClient ftpClient) {
boolean flag = false;
try {
// 轉(zhuǎn)移工作目錄至指定目錄下
boolean change = ftpClient.changeWorkingDirectory(filePath);
// 設置1M緩沖
ftpClient.setBufferSize(1024);
// 設置被動模式
ftpClient.enterLocalPassiveMode();
// 設置以二進制方式傳輸
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
FileInputStream in = new FileInputStream(new File(localPath
+ fileName));
if (change) {
flag = ftpClient.storeFile(fileName, in);
if (flag) {
System.out.println("上傳文件:" + fileName + " 成功");
} else {
System.out.println("上傳文件:" + fileName + " 失敗");
}
}
in.close();
/*ftpClient.logout();*/
} catch (IOException e) {
flag = false;
System.out.println("上傳文件:" + fileName + " 失敗");
e.printStackTrace();
}
return flag;
}
/**
* 斷開遠程服務器連接
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:39
* @version V1.0
* @param ftpClient void
*/
public static synchronized boolean FTPDisConnect(FTPClient ftpClient) {
boolean flag=false;
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
flag=true;
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 查看文件內(nèi)是否已有命令
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:59
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @param orderId 命令ID
* @return String
*/
public static String queryPlanInFile(String localPath, String fileName,String orderId) {
String result = "";
try {
FileReader file = new FileReader(localPath + fileName);
BufferedReader br = new BufferedReader(file);
LineNumberReader reader = new LineNumberReader(br);
String str = null;
while ((str = reader.readLine()) != null) {
if (str.indexOf(orderId+":") == 0) {
result += str + "\r\n";
while ((str = reader.readLine()) != null) {
if ("".equals(str)) {
break;
}
result += str + "\r\n";
}
break;
}
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 添加命令到已有文件末尾
* @author LuoJiaLei
* @date 2019年2月13日 下午3:52:16
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @param orderId 命令ID
* @param planOrder 命令內(nèi)容
* @return boolean
*/
public static boolean addPlanAppendFile(String localPath, String fileName,String planOrder) {
boolean flag = false;
File file = new File(localPath + fileName);
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
if (!file.exists()) {
boolean hasFile = file.createNewFile();
if (hasFile) {
System.out.println("文件不存在,請創(chuàng)建該文件");
}
fos = new FileOutputStream(file);
} else {
fos = new FileOutputStream(file, true);
}
osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(planOrder);
flag = true;
System.out.println("寫入內(nèi)容成功");
} catch (Exception e) {
flag = false;
System.out.println("寫入內(nèi)容失敗");
e.printStackTrace();
} finally {
// 關(guān)閉流
try {
if (osw != null) {
osw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 替換原有的命令
* @author LuoJiaLei
* @date 2019年2月13日 下午3:52:54
* @version V1.0
* @param localPath 文件路徑
* @param fileName 文件名
* @param originalOrder 需修改的命令
* @param planOrder 命令內(nèi)容
* @return boolean
*/
public static boolean replacePlanInFile(String localPath, String fileName,String originalOrder, String planOrder) {
boolean flag = false;
try {
FileReader file = new FileReader(localPath + fileName); // 創(chuàng)建文件輸入流
BufferedReader br = new BufferedReader(file);
char[] data = new char[1024]; // 創(chuàng)建緩沖字符數(shù)組
int rn = 0;
StringBuilder sb = new StringBuilder(); // 創(chuàng)建字符串構(gòu)建器
// fis.read(data):將字符讀入數(shù)組。在某個輸入可用、發(fā)生 I/O
// 錯誤或者已到達流的末尾前,此方法一直阻塞。讀取的字符數(shù),如果已到達流的末尾,則返回 -1
while ((rn = file.read(data)) > 0) { // 讀取文件內(nèi)容到字符串構(gòu)建器
String str = String.valueOf(data, 0, rn);// 把數(shù)組轉(zhuǎn)換成字符串
sb.append(str);
}
file.close();// 關(guān)閉輸入流
// 從構(gòu)建器中生成字符串,并替換搜索文本
String str = sb.toString().replace(originalOrder, planOrder);
str=str.replaceAll("(?m)^\\s*$"+System.lineSeparator(), "\r\n"); //移除多余空行
FileWriter fout = new FileWriter(localPath + fileName);// 創(chuàng)建文件輸出流
fout.write(str.toCharArray());// 把替換完成的字符串寫入文件內(nèi)
fout.close();// 關(guān)閉輸出流
flag = true;
} catch (FileNotFoundException e) {
System.out.println("未找到文件");
e.printStackTrace();
flag = false;
} catch (IOException e) {
e.printStackTrace();
flag = false;
}
return flag;
}
/**
* 刪除本地文件
* @author LuoJiaLei
* @date 2019年2月13日 下午3:53:13
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @return boolean
*/
public static boolean removeLocalFile(String localPath, String fileName) {
boolean flag = false;
File file = new File(localPath + fileName);
if (!file.exists()) {
flag = false;
} else {
file.delete();
flag = true;
}
return flag;
}
}
linux版本:、 區(qū)別點:
1、讀數(shù)據(jù)時候的換行符區(qū)別
2、ftpclient的被動模式設置,linux的某些端口問題
關(guān)鍵語法
str=str.replaceAll(System.lineSeparator(), "\r\n"); //轉(zhuǎn)換換行符
str=str.replaceAll("(\r\n){3,}", "\r\n\r\n"); //移除多余空行
// 設置被動模式
ftpClient.enterLocalPassiveMode();
package com.enjoyor.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FTP協(xié)議工具類用于linux系統(tǒng)
* @author LuoJiaLei
*
*/
public class FTPUtilLinux {
/**
* ftp登錄驗證
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:12
* @version V1.0
* @param ftpIP ftp站點 IP地址
* @param ftpPort ftp站點 端口
* @param ftpUserName ftp站點 登錄用戶名
* @param ftpPassword ftp站點 密碼
* @return FTPClient ftp客戶端連接信息
*/
public static synchronized FTPClient FTPConnect(String ftpIP, int ftpPort,String ftpUserName, String ftpPassword) {
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");// 解決上傳文件時文件名亂碼
int reply = 0;
try {
// 連接至服務器
ftpClient.connect(ftpIP, ftpPort);
// 登錄服務器
ftpClient.login(ftpUserName, ftpPassword);
// 登陸成功,返回碼是230
reply = ftpClient.getReplyCode();
// 判斷返回碼是否合法
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.out.println("未連接到FTP,用戶名或密碼錯誤。");
ftpClient = null;
} else {
System.out.println("FTP連接成功。");
}
} catch (SocketException e) {
ftpClient = null;
System.out.println("FTP的端口錯誤,請正確配置。");
e.printStackTrace();
} catch (IOException e) {
ftpClient = null;
System.out.println("FTP的IP地址可能錯誤,請正確配置。");
e.printStackTrace();
}
return ftpClient;
}
/**
* 判斷服務器路徑是否存在
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:34
* @version V1.0
* @param path 路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static boolean FTPExistPath(String filePath, FTPClient ftpClient) {
boolean flag = false;
FTPFile[] ftpFileArr;
try {
//設置被動模式 linux環(huán)境下listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
ftpFileArr = ftpClient.listFiles(filePath);
if (ftpFileArr.length > 0) {
flag = true;
System.out.println("文件存在");
} else {
System.out.println("文件不存在");
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 判斷服務器文件是否存在
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:34
* @version V1.0
* @param path 路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static boolean FTPExistFile(String filePath,String fileName, FTPClient ftpClient) {
boolean flag = false;
try {
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(filePath);
// 檢驗文件是否存在
InputStream is = ftpClient.retrieveFileStream(fileName);
if(is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE){
return false;
}
if(is != null){
is.close();
ftpClient.completePendingCommand();
}
return true;
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 刪除ftp文件
* @author LuoJiaLei
* @date 2019年2月13日 下午3:50:33
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPDeleteFile(String filePath,String fileName, FTPClient ftpClient) {
boolean flag = false;
try {
System.out.println("開始刪除文件");
// 切換FTP目錄
//設置被動模式 linux環(huán)境listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(filePath);
ftpClient.dele(fileName);
/*ftpClient.logout();*/
flag = true;
System.out.println("刪除文件成功");
} catch (Exception e) {
System.out.println("刪除文件失敗");
e.printStackTrace();
}
return flag;
}
/**
* 下載ftp文件到本地
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:12
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param localPath 本地路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPDownload(String filePath,String fileName, String localPath, FTPClient ftpClient) {
boolean flag = false;
try {
//設置被動模式 linux環(huán)境listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
// 轉(zhuǎn)移到FTP服務器目錄至指定的目錄下
ftpClient.changeWorkingDirectory(filePath);
// 獲取文件列表
FTPFile[] fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(), is);
is.close();
}
}
/*ftpClient.logout();*/
flag = true;
System.out.println("下載文件:" + fileName + " 成功");
} catch (IOException e) {
flag = false;
System.out.println("下載文件:" + fileName + " 失敗");
e.printStackTrace();
}
return flag;
}
/**
* 本地上傳文件到ftp
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:23
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param localPath 本地路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPUpload(String filePath,String fileName, String localPath, FTPClient ftpClient) {
boolean flag = false;
try {
//換行符轉(zhuǎn)換
FileReader file = new FileReader(localPath + fileName);
BufferedReader br = new BufferedReader(file);
char[] data = new char[1024];
int rn = 0;
StringBuilder sb = new StringBuilder();
while ((rn = file.read(data)) > 0) {
String str = String.valueOf(data, 0, rn);
sb.append(str);
}
file.close();
String str=sb.toString();
str=str.replaceAll(System.lineSeparator(), "\r\n"); //轉(zhuǎn)換換行符
str=str.replaceAll("(\r\n){3,}", "\r\n\r\n"); //移除多余空行
FileWriter fout = new FileWriter(localPath + fileName);
fout.write(str.toCharArray());
fout.close();
// 轉(zhuǎn)移工作目錄至指定目錄下
boolean change = ftpClient.changeWorkingDirectory(filePath);
// 設置1M緩沖
ftpClient.setBufferSize(1024);
// 設置被動模式
ftpClient.enterLocalPassiveMode();
// 設置以二進制方式傳輸
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
FileInputStream in = new FileInputStream(new File(localPath
+ fileName));
if (change) {
flag = ftpClient.storeFile(fileName, in);
if (flag) {
System.out.println("上傳文件:" + fileName + " 成功");
} else {
System.out.println("上傳文件:" + fileName + " 失敗");
}
}
in.close();
/*ftpClient.logout();*/
} catch (IOException e) {
flag = false;
System.out.println("上傳文件:" + fileName + " 失敗");
e.printStackTrace();
}
return flag;
}
/**
* 斷開遠程服務器連接
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:39
* @version V1.0
* @param ftpClient void
*/
public static synchronized boolean FTPDisConnect(FTPClient ftpClient) {
boolean flag=false;
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
flag=true;
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 查看文件內(nèi)是否已有命令
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:59
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @param orderId 命令ID
* @return String
*/
public static String queryPlanInFile(String localPath, String fileName,String orderId) {
String result = "";
try {
FileReader file = new FileReader(localPath + fileName);
BufferedReader br = new BufferedReader(file);
LineNumberReader reader = new LineNumberReader(br);
String str = null;
while ((str = reader.readLine()) != null) {
if (str.indexOf(orderId+":") == 0) {
result += str + "\n";
while ((str = reader.readLine()) != null) {
if ("".equals(str)) {
break;
}
result += str + "\n";
}
break;
}
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 添加命令到已有文件末尾
* @author LuoJiaLei
* @date 2019年2月13日 下午3:52:16
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @param orderId 命令ID
* @param planOrder 命令內(nèi)容
* @return boolean
*/
public static boolean addPlanAppendFile(String localPath, String fileName, String planOrder) {
boolean flag = false;
File file = new File(localPath + fileName);
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
if (!file.exists()) {
boolean hasFile = file.createNewFile();
if (hasFile) {
System.out.println("文件不存在,請創(chuàng)建該文件");
}
fos = new FileOutputStream(file);
} else {
fos = new FileOutputStream(file, true);
}
osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(planOrder);
flag = true;
System.out.println("寫入內(nèi)容成功");
} catch (Exception e) {
flag = false;
System.out.println("寫入內(nèi)容失敗");
e.printStackTrace();
} finally {
// 關(guān)閉流
try {
if (osw != null) {
osw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 替換原有的命令
* @author LuoJiaLei
* @date 2019年2月13日 下午3:52:54
* @version V1.0
* @param localPath 文件路徑
* @param fileName 文件名
* @param oriOrder 需修改的命令
* @param planOrder 命令內(nèi)容
* @return boolean
*/
public static boolean replacePlanInFile(String localPath, String fileName,String oriOrder, String planOrder) {
boolean flag = false;
try {
FileReader file = new FileReader(localPath + fileName); // 創(chuàng)建文件輸入流
BufferedReader br = new BufferedReader(file);
char[] data = new char[1024]; // 創(chuàng)建緩沖字符數(shù)組
int rn = 0;
StringBuilder sb = new StringBuilder(); // 創(chuàng)建字符串構(gòu)建器
// fis.read(data):將字符讀入數(shù)組。在某個輸入可用、發(fā)生 I/O
// 錯誤或者已到達流的末尾前,此方法一直阻塞。讀取的字符數(shù),如果已到達流的末尾,則返回 -1
while ((rn = file.read(data)) > 0) { // 讀取文件內(nèi)容到字符串構(gòu)建器
String str = String.valueOf(data, 0, rn);// 把數(shù)組轉(zhuǎn)換成字符串
sb.append(str);
}
file.close();// 關(guān)閉輸入流
// 從構(gòu)建器中生成字符串,并替換搜索文本
String str = sb.toString().replace(oriOrder, planOrder);
FileWriter fout = new FileWriter(localPath + fileName);// 創(chuàng)建文件輸出流
fout.write(str.toCharArray());// 把替換完成的字符串寫入文件內(nèi)
fout.close();// 關(guān)閉輸出流
flag = true;
} catch (FileNotFoundException e) {
System.out.println("未找到文件");
e.printStackTrace();
flag = false;
} catch (IOException e) {
e.printStackTrace();
flag = false;
}
return flag;
}
/**
* 刪除本地文件
* @author LuoJiaLei
* @date 2019年2月13日 下午3:53:13
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @return boolean
*/
public static boolean removeLocalFile(String localPath, String fileName) {
boolean flag = false;
File file = new File(localPath + fileName);
if (!file.exists()) {
flag = false;
} else {
file.delete();
flag = true;
}
return flag;
}
}
針對中文編碼亂碼問題的修改
package com.enjoyor.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FTP協(xié)議工具類用于linux系統(tǒng)
* @author LuoJiaLei
*
*/
public class FTPUtilLinux {
private static final Logger logger = LoggerFactory.getLogger(FTPUtilLinux.class);
/**
* ftp登錄驗證
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:12
* @version V1.0
* @param ftpIP ftp站點 IP地址
* @param ftpPort ftp站點 端口
* @param ftpUserName ftp站點 登錄用戶名
* @param ftpPassword ftp站點 密碼
* @return FTPClient ftp客戶端連接信息
*/
public static synchronized FTPClient FTPConnect(String ftpIP, int ftpPort,String ftpUserName, String ftpPassword) {
FTPClient ftpClient = new FTPClient();
// 解決上傳文件時文件名與中文路徑亂碼
ftpClient.setControlEncoding("iso-8859-1");
int reply = 0;
try {
// 連接至服務器
ftpClient.connect(ftpIP, ftpPort);
// 登錄服務器
ftpClient.login(ftpUserName, ftpPassword);
// 登陸成功,返回碼是230
reply = ftpClient.getReplyCode();
// 判斷返回碼是否合法
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
logger.info("未連接到FTP,用戶名或密碼錯誤。");
ftpClient = null;
} else {
logger.info("FTP連接成功。");
}
} catch (SocketException e) {
ftpClient = null;
logger.info("FTP的端口錯誤,請正確配置。");
e.printStackTrace();
} catch (IOException e) {
ftpClient = null;
logger.info("FTP的IP地址錯誤,請正確配置。");
e.printStackTrace();
}
return ftpClient;
}
/**
* 判斷服務器路徑是否存在
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:34
* @version V1.0
* @param path 路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static boolean FTPExistPath(String filePath, FTPClient ftpClient) {
boolean flag = false;
FTPFile[] ftpFileArr;
try {
//設置被動模式 linux環(huán)境下listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
ftpFileArr = ftpClient.listFiles(filePath);
if (ftpFileArr.length > 0) {
flag = true;
logger.info("文件存在");
} else {
logger.info("文件不存在");
}
} catch (IOException e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPExistPath() -> 路徑讀取異常");
}
return flag;
}
/**
* 判斷服務器文件是否存在
* @author LuoJiaLei
* @date 2019年2月13日 下午3:49:34
* @version V1.0
* @param path 路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static boolean FTPExistFile(String filePath,String fileName, FTPClient ftpClient) {
boolean flag = false;
InputStream is = null;
try {
// 設置被動模式 linux環(huán)境下listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(filePath);
// 檢驗文件是否存在
is = ftpClient.retrieveFileStream(fileName);
if (is == null
|| ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
return false;
}
return true;
} catch (IOException e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPExistFile() -> 文件流讀取異常");
} finally {
try {
if (is != null) {
is.close();
ftpClient.completePendingCommand();
}
} catch (Exception e2) {
e2.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPExistFile() -> 文件流關(guān)閉異常");
}
}
return flag;
}
/**
* 刪除ftp文件
* @author LuoJiaLei
* @date 2019年2月13日 下午3:50:33
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPDeleteFile(String filePath,String fileName, FTPClient ftpClient) {
boolean flag = false;
try {
// 設置被動模式 linux環(huán)境listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
// 切換FTP目錄
ftpClient.changeWorkingDirectory(filePath);
ftpClient.dele(fileName);
logger.info("刪除文件成功");
return true;
} catch (Exception e) {
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPDeleteFile() -> 刪除文件失敗");
e.printStackTrace();
}
return flag;
}
/**
* 下載ftp文件到本地
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:12
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param localPath 本地路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPDownload(String filePath,String fileName, String localPath, FTPClient ftpClient) {
boolean flag = false;
try {
// 設置被動模式 linux環(huán)境listFiles和retrieveFile方法報錯解決方案
ftpClient.enterLocalPassiveMode();
// 轉(zhuǎn)移到FTP服務器目錄至指定的目錄下
ftpClient.changeWorkingDirectory(filePath);
// 獲取文件列表
FTPFile[] fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(), is);
is.close();
}
}
logger.info("下載文件:" + fileName + " 成功");
return true;
} catch (IOException e) {
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPDownload() -> 下載文件:" + fileName + " 失敗");
e.printStackTrace();
}
return flag;
}
/**
* 本地上傳文件到ftp
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:23
* @version V1.0
* @param filePath 文件路徑
* @param fileName 文件名
* @param localPath 本地路徑
* @param ftpClient ftp客戶端連接信息
* @return boolean
*/
public static synchronized boolean FTPUpload(String filePath,String fileName, String localPath, FTPClient ftpClient) {
boolean flag = false;
InputStreamReader isr =null;
BufferedReader br=null;
Writer writer=null;
FileInputStream in=null;
try {
// 以GBK編碼讀文件
isr = new InputStreamReader(new FileInputStream(new File(localPath
+ fileName)), "GBK");
br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + System.lineSeparator());
}
String str = sb.toString();
// 轉(zhuǎn)換換行符
str = str.replaceAll(System.lineSeparator(), "\r\n");
// 移除多余空行
str = str.replaceAll("(\r\n){3,}", "\r\n\r\n");
// 以so-8859-1編碼寫文件
writer = new OutputStreamWriter(new FileOutputStream(new File(
localPath + fileName)), "iso-8859-1");
String strFinal = new String(str.getBytes("GBK"), "iso-8859-1");
writer.write(strFinal.toCharArray());
writer.close();
// 轉(zhuǎn)移工作目錄至指定目錄下
boolean change = ftpClient.changeWorkingDirectory(filePath);
// 設置1M緩沖
ftpClient.setBufferSize(1024);
// 設置被動模式
ftpClient.enterLocalPassiveMode();
// 設置以二進制方式傳輸
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
in = new FileInputStream(new File(localPath + fileName));
if (change) {
flag = ftpClient.storeFile(fileName, in);
if (flag) {
logger.info("上傳文件:" + fileName + " 成功");
} else {
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPUpload() -> 上傳文件:"
+ fileName + " 失敗");
}
}
} catch (IOException e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPUpload() -> 上傳文件:"
+ fileName + " 異常");
return false;
} finally {
try {
if (isr != null) {
isr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPUpload() -> 讀文件流 關(guān)閉異常");
}
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPUpload() -> 上傳文件流 關(guān)閉異常");
}
}
return flag;
}
/**
* 斷開遠程服務器連接
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:39
* @version V1.0
* @param ftpClient void
*/
public static synchronized boolean FTPDisConnect(FTPClient ftpClient) {
boolean flag=false;
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
return true;
} catch (IOException e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPDisConnect() -> 斷開連接失敗");
}
}
return flag;
}
/**
* 查看文件內(nèi)是否已有命令
* @author LuoJiaLei
* @date 2019年2月13日 下午3:51:59
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @param orderId 命令ID
* @return String
*/
public static String queryPlanInFile(String localPath, String fileName,String orderId) {
String result = "";
InputStreamReader isr =null;
try {
File file = new File(localPath + fileName);
isr=new InputStreamReader(new FileInputStream(file), "GBK");
BufferedReader br = new BufferedReader(isr);
LineNumberReader reader = new LineNumberReader(br);
String str = null;
while ((str = reader.readLine()) != null) {
if (str.indexOf(orderId+":") == 0) {
result += str + "\n";
while ((str = reader.readLine()) != null) {
if ("".equals(str)) {
break;
}
result += str + "\n";
}
break;
}
}
isr.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 添加命令到已有文件末尾
* @author LuoJiaLei
* @date 2019年2月13日 下午3:52:16
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @param orderId 命令ID
* @param planOrder 命令內(nèi)容
* @return boolean
*/
public static boolean addPlanAppendFile(String localPath, String fileName, String planOrder) {
boolean flag = false;
File file = new File(localPath + fileName);
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
if (!file.exists()) {
boolean hasFile = file.createNewFile();
if (hasFile) {
logger.info("文件不存在,請創(chuàng)建該文件");
}
fos = new FileOutputStream(file);
} else {
fos = new FileOutputStream(file, true);
}
// 將輸入命令轉(zhuǎn)換為iso-8859-1編碼
String planOrderFinal = new String(planOrder.getBytes("GBK"),
"iso-8859-1");
// 將文件以iso-8859-1寫入
osw = new OutputStreamWriter(fos, "iso-8859-1");
osw.write(planOrderFinal);
logger.info("寫入內(nèi)容成功");
return true;
} catch (Exception e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->addPlanAppendFile() -> 寫入內(nèi)容失敗");
} finally {
// 關(guān)閉流
try {
if (osw != null) {
osw.close();
}
} catch (IOException e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->addPlanAppendFile() -> 寫文件流 關(guān)閉失敗");
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->addPlanAppendFile() -> 讀文件流 關(guān)閉失敗");
}
}
return flag;
}
/**
* 替換原有的命令
* @author LuoJiaLei
* @date 2019年2月13日 下午3:52:54
* @version V1.0
* @param localPath 文件路徑
* @param fileName 文件名
* @param oriOrder 需修改的命令
* @param planOrder 命令內(nèi)容
* @return boolean
*/
public static boolean replacePlanInFile(String localPath, String fileName,String oriOrder, String planOrder) {
boolean flag = false;
InputStreamReader isr = null;
BufferedReader br = null;
Writer writer = null;
try {
// 以GBK編碼讀文件
isr = new InputStreamReader(new FileInputStream(new File(localPath
+ fileName)), "GBK");
br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + System.lineSeparator());
}
String str = sb.toString().replace(oriOrder, planOrder);
// 以so-8859-1編碼寫文件
writer = new OutputStreamWriter(new FileOutputStream(new File(
localPath + fileName)), "iso-8859-1");
// 修改字符串編碼為iso-8859-1
String strFinal = new String(str.getBytes("GBK"), "iso-8859-1");
writer.write(strFinal.toCharArray());
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->replacePlanInFile() -> 未找到文件");
} catch (IOException e) {
e.printStackTrace();
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->replacePlanInFile() -> 文件流讀取異常");
} finally {
try {
if (isr != null) {
isr.close();
}
} catch (Exception e2) {
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->replacePlanInFile() -> 讀文件流 關(guān)閉異常");
}
try {
if (writer != null) {
writer.close();
}
} catch (Exception e2) {
logger.info("package com.enjoyor.utils -> FTPUtilLinux ->replacePlanInFile() -> 寫文件流 關(guān)閉異常");
}
}
return flag;
}
/**
* 刪除本地文件
* @author LuoJiaLei
* @date 2019年2月13日 下午3:53:13
* @version V1.0
* @param localPath 本地路徑
* @param fileName 文件名
* @return boolean
*/
public static boolean removeLocalFile(String localPath, String fileName) {
boolean flag = false;
File file = new File(localPath + fileName);
if (file.exists()) {
file.delete();
return true;
}
return flag;
}
}
以上代碼均以Linux環(huán)境考慮編碼和空格,Windows環(huán)境使用時要注意