获取ftp上指定的文本文件并返回string字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/l18848956739/article/details/88670725
/**
 * @Description: 读取ftp上的文本文件
 * @param: [ftpDirName, fileName, strencoding]
 * @return: java.lang.String
 */
public String readFile(String ftpDirName, String fileName) {
    InputStream ins;
    StringBuilder builder = new StringBuilder();
    try {
        if ("".equals(ftpDirName)) {
            ftpDirName = "/";
        }
        String dir = new String(ftpDirName.getBytes("GBK"), "iso-8859-1");
        if (!ftp.changeWorkingDirectory(dir)) {
            log.error("切换目录失败:" + ftpDirName);
        }
        fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
        // 从服务器上读取指定的文件
        ins = ftp.retrieveFileStream(fileName);
        BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line + System.getProperty("line.separator"));
        }
        reader.close();
        if (ins != null) {
            ins.close();
        }
        // 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
        ftp.getReply();
        ftp.logout();
        return builder.toString();
    } catch (Exception e) {
        log.error("读取ftp文件出现异常", e);
        return "";
    }
}

猜你喜欢

转载自blog.csdn.net/l18848956739/article/details/88670725