Java noob пробует свои силы в базовом FTP. Попытка превратить учебник Apache Commons Net FTP в работающую программу, в которой пользователи вводят сервер, пользователя, проходят и могут изменять / добавлять / просматривать / удалять файлы.
Однако всякий раз, когда я получаю команду «list files», я получаю необычную ошибку. Ошибка:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The import org.apache.oro cannot be resolved
The import org.apache.oro cannot be resolved
The import org.apache.oro cannot be resolved
The import org.apache.oro cannot be resolved
The import org.apache.oro cannot be resolved
The import org.apache.oro cannot be resolved
Pattern cannot be resolved to a type
MatchResult cannot be resolved to a type
PatternMatcher cannot be resolved to a type
_matcher_ cannot be resolved
Perl5Matcher cannot be resolved to a type
pattern cannot be resolved
Perl5Compiler cannot be resolved to a type
MalformedPatternException cannot be resolved to a type
result cannot be resolved or is not a field
_matcher_ cannot be resolved
pattern cannot be resolved or is not a field
result cannot be resolved or is not a field
_matcher_ cannot be resolved
result cannot be resolved or is not a field
result cannot be resolved or is not a field
result cannot be resolved or is not a field
result cannot be resolved or is not a field
result cannot be resolved or is not a field
result cannot be resolved or is not a field
result cannot be resolved or is not a field
at org.apache.commons.net.ftp.parser.RegexFTPFileEntryParserImpl.<init>(RegexFTPFileEntryParserImpl.java:19)
at org.apache.commons.net.ftp.parser.ConfigurableFTPFileEntryParserImpl.<init>(ConfigurableFTPFileEntryParserImpl.java:57)
at org.apache.commons.net.ftp.parser.UnixFTPEntryParser.<init>(UnixFTPEntryParser.java:136)
at org.apache.commons.net.ftp.parser.UnixFTPEntryParser.<init>(UnixFTPEntryParser.java:119)
at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createUnixFTPEntryParser(DefaultFTPFileEntryParserFactory.java:169)
at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createFileEntryParser(DefaultFTPFileEntryParserFactory.java:94)
at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:2359)
at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2142)
at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2188)
at ftpconnecter.FTPConnecter.run(FTPConnecter.java:74)
at ftpconnecter.Main.main(Main.java:11)
Сам класс ниже. Ввод пустой строки для пути в makeDir - это то, что вызывает ошибку. Тем не менее, сообщение об ошибке говорит, что это происходит в строке 74, что является другим, если для метода createDir. Там также нет исключений, которые я не видел раньше в сообщении об ошибке Java.
В качестве вспомогательного вопроса, является ли способ, которым я настраиваю этот метод, с одним большим блоком try-catch, эффективным способом структурирования этой программы?
package ftpconnecter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPConnecter {
public void run() {
Scanner reader = new Scanner(System.in);
while(true) {
System.out.println("Connect to FTP? (Anything other than Yes quits app)");
String input = reader.nextLine();
if (!input.equals("Yes")) {
break;
}
System.out.println("Server address?");
String server = reader.nextLine().trim();
System.out.println("Username");
String user = reader.nextLine();
System.out.println("Password:");
String pass = reader.nextLine();
int port = 21;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Connect failed");
continue;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
continue;
}
while(true) {
System.out.println("Commands: " + "\n" +
"1. List Files & Directories (L)" + "\n" +
"2. Create New Directory (D)" + "\n" +
"3. Create Nested Directory (N)");
String command = reader.nextLine();
if (command.equals("L")) {
System.out.println("What is the file path? (Press enter for all)");
String filePath = reader.nextLine();
FTPFile[] files = ftpClient.listFiles(filePath);
printFileDetails(files);
} else if (command.equals("D")) {
createDir(ftpClient);
} else if (command.equals("N")) {
System.out.println("What is your directory path?");
String path = reader.nextLine();
makeDir(ftpClient, path);
} else {
break;
}
}
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException ex) {
System.out.println("Oops! Something went wrong");
ex.printStackTrace();
}
}
}
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);
}
}
}
private void createDir(FTPClient ftpClient) throws IOException {
Scanner reader = new Scanner(System.in);
System.out.println("What is the directory to be created?");
String dirToCreate = reader.nextLine();
boolean 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.");
}
}
private void makeDir(FTPClient ftpClient, String dirPath) throws IOException {
String[] pathElements = dirPath.split("/");
if (pathElements != null && pathElements.length > 0) {
for (String singleDir : pathElements) {
boolean exists = ftpClient.changeWorkingDirectory(singleDir);
if (!exists) {
boolean created = ftpClient.makeDirectory(singleDir);
if (created) {
System.out.println("Created directory " + singleDir);
} else {
System.out.println("Could not create directory " + singleDir);
}
}
}
}
}
private void printFileDetails(FTPFile[] files) {
DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (FTPFile file : files) {
String details = file.getName();
if (file.isDirectory()) {
details = "[" + details + "]";
}
details += "\t\t" + file.getSize();
details += "\t\t" + dateFormater.format(file.getTimestamp().getTime());
System.out.println(details);
}
}
}