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

时间:2015-03-07 08:05:57

标签: java ftp apache-commons-net

做过测试,用java读取ftp文件,工具是apache-common-net ftp.I尝试读取一个文件,没关系,但是当我读取目录中的多个文件时,InputStream(ftpClient.retrieveFileStream) )是空的。

有人可以帮助,谢谢。

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();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我使用的解决方案是创建两个不同的FTP连接,以便从两个不同的文件中读取数据。 代码如下:

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();