我需要有关Java Networking编程的帮助。我试图创建一个新的文本文件到FTP服务器。我在Internet上找到了此代码示例,但它仅创建一个目录。如何将其更改为文本文件格式?
这是代码:
public class FTPCreateDirDemo {
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
public static void main(String[] args) {
String server = "www.yourserver.com";
int port = 21;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
}
// Creates a directory
String dirToCreate = "/upload123";
success = ftpClient.makeDirectory(dirToCreate);
showServerReply(ftpClient);
if (success) {
System.out.println("Successfully created directory: " + dirToCreate);
} else {
System.out.println("Failed to create directory. See server's reply.");
}
// logs out
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
对不起,我的英语不好。
我不是该库的专家,但我认为FTP不仅仅是从远程服务器发送/接收文件,而不仅仅是直接访问远程文件系统。因此,要创建远程文件,您应该首先在本地(例如,在临时目录中)创建它,然后将其发送到远程服务器。检查文档:https : //commons.apache.org/proper/commons-net/javadocs/api-1.4.1/org/apache/commons/net/ftp/FTPClient.html
尤其是这种方法:
public boolean storeFile(String remote, InputStream local)
throws IOException
给定本地文件“ foo.txt”,您可以创建一个InputStream并使用该输入流将文件发送到远程端:
try (FileInputStream inputStream = new FileInputStream("foo.txt");) {
ftpClient.storeFile("foo.txt", inputStream);
}
[edit]请注意,由于这些方法将InputStream作为参数,因此最终可以使用本地文件以外的其他内容作为输入:您也可以直接从String读取。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句