简体   繁体   English

Java Ftp列表目录然后逐个读取文本文件,但输入流为空

[英]Java Ftp list directory then read text file one by one,but the input stream is null

Did a test,using java to read ftp file,the tools is apache-common-net ftp.I try to read one file,it's ok,but when I read multiple files in a directory,the InputStream(ftpClient.retrieveFileStream) is null. 做过测试,使用java来读取ftp文件,这些工具是apache-common-net ftp.I尝试读取一个文件,没关系,但是当我读取目录中的多个文件时,InputStream(ftpClient.retrieveFileStream)为null 。

Can someone help please,thanks. 请有人帮忙,谢谢。

private static FTPClient ftpClient = new FTPClient();
private static String encoding = System.getProperty("file.encoding");

public static void main(String[] args) {
    ftpClient.setControlEncoding(encoding);
    try {
        ftpClient.connect("host", 21);

        ftpClient.login("user", "password");

        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

        int reply = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.out.println("connection error!");
            System.exit(0);
        }

        ftpClient.changeWorkingDirectory(new String("/home/neal/test/"
                .getBytes(encoding), "iso-8859-1"));

        FTPFile[] fs = ftpClient.listFiles();
        for (FTPFile f : fs) {
            // read all txt file
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(ftpClient.retrieveFileStream(f.getName())));//the input stream will be null
            reader.readLine();
        }
        ftpClient.logout();//

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

The solution that I've used was to create two different connection to the FTP in order to read the data from the two different files. 我使用的解决方案是创建两个不同的FTP连接,以便从两个不同的文件中读取数据。 Code below : 代码如下:

SCFTPClient ftpC = new SCFTPClient("localhost", "admin", "admin", 2222); String active = ftpC.readFile(file1); ftpC.disconnect(); SCFTPClient ftpC2 = new SCFTPClient("localhost", "admin", "admin", 2222); if (null != active) { file = ftpC2.readFile(file2); } else { file = ftpC2.readFile(fileName); } ftpC2.disconnect();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM