0

我正在读取 FTP 服务器上的文件并将该数据写入另一个文件。但是在正确读取数据后,我无法将文件写入 FTP 服务器。

我可以使用“检索文件”检索文件,但不能使用该storefile功能存储文件。

我的代码是:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class FtpDemo {

public static void main(String args[]){

FTPClient client=new FTPClient();       
try {
                if(client.isConnected()){
                    client.disconnect();
                    Boolean isLog=client.logout();
                    System.out.println(isLog);
                }

                client.connect("server");
                Boolean isLogin=client.login("user","password");

                if(isLogin){
                    System.out.println("Login has been successfully");
                    FTPFile[] files=client.listFiles();
                    System.out.println("Login has been successfully"+files.length);
                    for(int i=0;i<files.length;i++){
                        if(files[i].getName().equals("rajesh.txt")){
                            System.out.println("match has been successfully");
                            InputStream is=client.retrieveFileStream("/rajesh.txt");
                            BufferedReader br=new BufferedReader(new InputStreamReader(is));
                            String str;
                            String content="";
                            str=br.readLine();

                            while(str!=null){
                                content+=str;
                                str=br.readLine();
                            }

                            System.out.println(content);
                            Boolean isStore=client.storeFile("/rajesh.txt",is);
                            System.out.println(isStore);
                        }
                    }
                }
            }
            catch(Exception e){
                System.out.println(e.getMessage());
            }
        }
}
4

1 回答 1

0

几点,is被读到最后br。新文件具有相同的名称。使用 Reader(文本)而不是 Stream(二进制数据)依赖于读取编码中的文本。最好使用流。

                        InputStream is=client.retrieveFileStream("/rajesh.txt");
                        final String encoding = "UTF-8"; // "Cp1252"?
                        BufferedReader br=new BufferedReader(new InputStreamReader(is, encoding));
                        String str;
                        String content="";
                        str=br.readLine();

                        while(str!=null){
                            content+=str + "\n"; // "\r\n"?
                            str=br.readLine();
                        }
                        br.close();

                        InputStream is2 = new ByteArrayInputStream(content.getBytes(encoding));

                        System.out.println(content);
                        Boolean isStore=client.storeFile("/rajesh2.txt",is2);
于 2012-05-02T07:13:04.547 回答