Java:JAVA通过FTP协议与IO流远程编辑文件

2019-12-23  本文已影响0人  不加糖L

应用场景:鉴于某些硬件设备的通信协议较为复杂,而其功能又依托底层文件实现。考虑直接修改其底层文件的方式来实现业务(安全性将再从网络与框架层面考虑)。

一、将需要修改的文件地址发布为FTP站点

1.开启Windows功能

FTP服务器.png TFTP客户端.png

2.通过ISS创建FTP站点

新建站点.png 连接方式.png 验证.png

3.创建用户

创建用户.png

二、Java代码实现

1.maven

<!-- FTP 协议-->
    <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协议工具类
 * @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环境下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环境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环境listFiles和retrieveFile方法报错解决方案
            ftpClient.enterLocalPassiveMode();
            // 转移到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 {
            // 转移工作目录至指定目录下
            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;
    }
    /**
     * 查看文件内是否已有命令  
     * @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     命令内容
     * @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("文件不存在,请创建该文件");
                }
                fos = new FileOutputStream(file);
            } else {
                fos = new FileOutputStream(file, true);
            }
            osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write(planOrder);
            flag = true;
            System.out.println("写入内容成功");
        } catch (Exception e) {
            flag = false;
            System.out.println("写入内容失败");
            e.printStackTrace();
        } finally {
            // 关闭流
            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      命令内容
     * @return boolean
     */
    public static boolean replacePlanInFile(String localPath, String fileName,String originalOrder, String planOrder) {
        boolean flag = false;
        try {
            FileReader file = new FileReader(localPath + fileName); // 创建文件输入流
            BufferedReader br = new BufferedReader(file);
            char[] data = new char[1024]; // 创建缓冲字符数组
            int rn = 0;
            StringBuilder sb = new StringBuilder(); // 创建字符串构建器
            // fis.read(data):将字符读入数组。在某个输入可用、发生 I/O
            // 错误或者已到达流的末尾前,此方法一直阻塞。读取的字符数,如果已到达流的末尾,则返回 -1
            while ((rn = file.read(data)) > 0) { // 读取文件内容到字符串构建器
                String str = String.valueOf(data, 0, rn);// 把数组转换成字符串
                sb.append(str);
            }
            file.close();// 关闭输入流
            // 从构建器中生成字符串,并替换搜索文本
            String str = sb.toString().replace(originalOrder, planOrder);
            str=str.replaceAll("(?m)^\\s*$"+System.lineSeparator(), "\r\n"); //移除多余空行
            FileWriter fout = new FileWriter(localPath + fileName);// 创建文件输出流
            fout.write(str.toCharArray());// 把替换完成的字符串写入文件内
            fout.close();// 关闭输出流
            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版本:、 区别点:

1、读数据时候的换行符区别

2、ftpclient的被动模式设置,linux的某些端口问题

关键语法

str=str.replaceAll(System.lineSeparator(), "\r\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协议工具类用于linux系统
 * @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环境下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环境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环境listFiles和retrieveFile方法报错解决方案
            ftpClient.enterLocalPassiveMode();
            // 转移到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 {
            //换行符转换
            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");   //转换换行符
            str=str.replaceAll("(\r\n){3,}", "\r\n\r\n"); //移除多余空行
            FileWriter fout = new FileWriter(localPath + fileName);
            fout.write(str.toCharArray());
            fout.close();
            // 转移工作目录至指定目录下
            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;
    }
    /**
     * 查看文件内是否已有命令  
     * @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     命令内容
     * @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("文件不存在,请创建该文件");
                }
                fos = new FileOutputStream(file);
            } else {
                fos = new FileOutputStream(file, true);
            }
            osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write(planOrder);
            flag = true;
            System.out.println("写入内容成功");
        } catch (Exception e) {
            flag = false;
            System.out.println("写入内容失败");
            e.printStackTrace();
        } finally {
            // 关闭流
            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      命令内容
     * @return boolean
     */
    public static boolean replacePlanInFile(String localPath, String fileName,String oriOrder, String planOrder) {
        boolean flag = false;
        try {
            FileReader file = new FileReader(localPath + fileName); // 创建文件输入流
            BufferedReader br = new BufferedReader(file);
            char[] data = new char[1024]; // 创建缓冲字符数组
            int rn = 0;
            StringBuilder sb = new StringBuilder(); // 创建字符串构建器
            // fis.read(data):将字符读入数组。在某个输入可用、发生 I/O
            // 错误或者已到达流的末尾前,此方法一直阻塞。读取的字符数,如果已到达流的末尾,则返回 -1
            while ((rn = file.read(data)) > 0) { // 读取文件内容到字符串构建器
                String str = String.valueOf(data, 0, rn);// 把数组转换成字符串
                sb.append(str);
            }
            file.close();// 关闭输入流
            // 从构建器中生成字符串,并替换搜索文本
            String str = sb.toString().replace(oriOrder, planOrder);
            FileWriter fout = new FileWriter(localPath + fileName);// 创建文件输出流
            fout.write(str.toCharArray());// 把替换完成的字符串写入文件内
            fout.close();// 关闭输出流
            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协议工具类用于linux系统
 * @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环境下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环境下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() -> 文件流关闭异常");
            }
        }
        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环境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环境listFiles和retrieveFile方法报错解决方案
            ftpClient.enterLocalPassiveMode();
            // 转移到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();
            // 转换换行符
            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();
            // 转移工作目录至指定目录下
            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() -> 读文件流 关闭异常");
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
                logger.info("package com.enjoyor.utils -> FTPUtilLinux ->FTPUpload() -> 上传文件流 关闭异常");
            }
        }
        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;
    }
    /**
     * 查看文件内是否已有命令  
     * @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     命令内容
     * @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("文件不存在,请创建该文件");
                }
                fos = new FileOutputStream(file);
            } else {
                fos = new FileOutputStream(file, true);
            }
            // 将输入命令转换为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("写入内容成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("package com.enjoyor.utils -> FTPUtilLinux ->addPlanAppendFile() -> 写入内容失败");
        } finally {
            // 关闭流
            try {
                if (osw != null) {
                    osw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.info("package com.enjoyor.utils -> FTPUtilLinux ->addPlanAppendFile() -> 写文件流 关闭失败");
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.info("package com.enjoyor.utils -> FTPUtilLinux ->addPlanAppendFile() -> 读文件流 关闭失败");
            }
        }
        return flag;
    }
    /**
     * 替换原有的命令 
     * @author LuoJiaLei
     * @date 2019年2月13日 下午3:52:54  
     * @version V1.0  
     * @param localPath      文件路径
     * @param fileName       文件名
     * @param oriOrder       需修改的命令
     * @param planOrder      命令内容
     * @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() -> 读文件流 关闭异常");
            }
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (Exception e2) {
                logger.info("package com.enjoyor.utils -> FTPUtilLinux ->replacePlanInFile() -> 写文件流 关闭异常");
            }
        }
        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环境考虑编码和空格,Windows环境使用时要注意

上一篇下一篇

猜你喜欢

热点阅读