[英]Could Not Write File on FTP server using FTPClient in Java
I am reading files on a FTP server and writing that data into another file. 我正在读取FTP服务器上的文件,并将该数据写入另一个文件。 But after properly reading the data I couldn't write the file on to the FTP server.
但是在正确读取数据之后,我无法将文件写入FTP服务器。
I can retrieve files using "retrieve file", but can not store file using the storefile
function. 我可以使用“检索文件”来检索文件,但是不能使用
storefile
函数存储文件。
My code is: 我的代码是:
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());
}
}
}
Several points, is
is read to the end by br
. 几点,
is
读取由最终br
。 The new file had the same name. 新文件具有相同的名称。 Using a Reader (text) instead of a Stream (binary data) relies on reading text in an encoding.
使用读取器(文本)代替流(二进制数据)依赖于读取编码中的文本。 Better use a 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.