简体   繁体   English

从FTP服务器读取文件,但InputStream始终为null

[英]Read a file from a FTP server but InputStream is always null

I want read files in a directory. 我想读取目录中的文件。 I want add in: List<String> nomi = new ArrayList<String>(); 我想添加: List<String> nomi = new ArrayList<String>(); the linestring of file Nomi.txt. 文件Nomi.txt的线串。

With debug i view correctly the files in links(001.jpg 002.jpg 003.jpg) and ft(Nomi.txt), but in stream i have always null; 通过调试,我可以正确查看links(001.jpg 002.jpg 003.jpg)和ft(Nomi.txt)中的文件,但在流中我始终为null;

InputStream stream = f.retrieveFileStream(/*url_ftp + "/photo/"+ft*/ft);

my complete code is this: 我完整的代码是这样的:

private static abstract class GetLinksTask extends AsyncTask<String, Void, List<String>> {

    protected List<String> doInBackground(String... urls) {
        List<String> links = new ArrayList<String>();
        String ft=null;
        BufferedReader reader = null;
        List<String> nomi = new ArrayList<String>();
        FTPClient f = new FTPClient();

        try {
            int reply;
            f.connect(url_ftp);
            f.login(username,password );
            reply = f.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                f.disconnect();
                System.err.println("FTP server refused connection.");
            }
            FTPListParseEngine engine = f.initiateListParsing("photo");

            while (engine.hasNext()) {
                FTPFile[] files = engine.getNext(25);  // "page size" you want
                //FTPFile[] files = engine.getFiles(filter);
                for (FTPFile file : files) {   
                    if(file.getName().substring(file.getName().length()-3,file.getName().length()).equals("jpg")){
                        System.out.println(file.getName());
                        links.add(file.getName());
                    }else{
                        ft=file.getName();
                        InputStream stream = f.retrieveFileStream(/*url_ftp + "/photo/"+ft*/ft);
                        reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                        //nomi.add(reader.readLine());                                 
                    }
                    System.out.println(file.getName());
                }
                //names=nomi;
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null)
                try {
                    reader.close();
                }catch (IOException logOrIgnore) {
            }
        }

        return links;
    }

    protected abstract void postExecute(List<String> links);

    protected void onPostExecute(List<String> lists) {
        postExecute(lists);
    }

}

Some tips? 一些技巧? thanks 谢谢

It is not enough to create a Reader 创建阅读器是不够的

reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));

and to close it: 并关闭它:

reader.close();

Somewhere, in between, you'll actually have to read the data: 在这之间的某个地方,您实际上必须读取数据:

String line;
while( (line = reader.readLine()) != null ){
    nomi.add( line );
}

I am explaining the full code of getting inputStream from FTP server and then how to read data from that inputstream. 我正在解释从FTP服务器获取inputStream的完整代码,然后说明如何从该inputstream读取数据。 I am assuming, you are using TLS/SSL security layer. 我假设您正在使用TLS / SSL安全层。

  public FTPSClient makeFTPConnection(String vserver, int vport, String vuser, String vpassword) {
    LOGGER.debug("ENTRY");
       try {
        ftpClient = new FTPSClient();
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {

        ftpClient.connect(vserver, vport);
        ftpClient.login(vuser, vpassword);

        ftpClient.execPBSZ(0);
        ftpClient.execPROT("P");
        ftpClient.changeWorkingDirectory("/");
        ftpClient.changeWorkingDirectory("/feeds");
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
  /*  //  int reply=ftpClient.getReply();
        String replyStr=ftpClient.getReplyString();
        ftpClient.getAuthValue();*/

    LOGGER.debug("EXIT");
    return ftpClient;
}

Then after making the connection, we will check weather file exist at ftp or not. 然后,建立连接后,我们将检查ftp是否存在天气文件。

  public InputStream checkWOFileExistAtFTP(FTPSClient ftpClient, String host,String user, String filePath) throws IOException {

    int returnCode;
   // filePath="ftp://"+user+"@"+host+"/"+filePath;
    InputStream inputStream = ftpClient.retrieveFileStream(filePath);

    String dd=ftpClient.getReplyString();
    returnCode = ftpClient.getReplyCode();
    if (inputStream == null || returnCode == 550) {
        return null;
    }
    return inputStream;

}

Now we already got the inputStream in above method now its time to read data from it. 现在我们已经在上面的方法中获得了inputStream,现在是时候从中读取数据了。

            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

            System.out.println("Reading file start.");

            char[] charBuffer = new char[8 * 1024];
            StringBuilder builder = new StringBuilder();
            int numCharsRead;
            while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) {
                builder.append(charBuffer, 0, numCharsRead);
            }
//will print all data 
system.out.println(builder.toString());

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

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