Eu preciso usar o Java para escrever uma ferramenta FTP, porque há apenas um pouco de básico do Java, mas como eu não o uso há vários anos, quase não posso fazer isso, então tenho que fazer um pouco Bit, mas felizmente eu posso buscá -lo.
No entanto, como eu uso o JAVAC para compilar no Linux, não usando o IDE para fazer essas coisas sob vitória, levei algum tempo para executar e compilar. . Alguns.
Para a ferramenta de download do FTP, o código é o seguinte:
A cópia do código é a seguinte:
importar java.io.file;
importar java.io.fileInputStream;
importar java.io.filenotfoundException;
importar java.io.fileOutputStream;
importar java.io.ioException;
importar java.io.inputStream;
importar java.io.OutputStream;
importar java.net.socketexception;
importar org.apache.commons.net.ftp.ftpClient;
importar org.apache.commons.net.ftp.ftpreply;
classe pública ftpclient {
host privado string;
private int porta;
Nome de usuário privado de string;
senha de sequência privada;
Binary BinaryTransfer privado = true;
passivemode booleano privado = true;
private string coding = "utf-8";
private int clienttimeout = 3000;
bandeira booleana privada = true;
private ftpClient ftpClient = null;
public string gethost () {
host de retorno;
}
public void sethost (host de string) {
this.host = host;
}
public int getport () {
porta de retorno;
}
public void Setport (int porta) {
this.port = porta;
}
public String getUserName () {
retornar nome de usuário;
}
public void SetUserName (String UserName) {
this.UserName = Nome de usuário;
}
public String getPassword () {
retornar senha;
}
public void setPassword (senha da string) {
this.password = senha;
}
public boolean isbinarytransfer () {
retornar binarytransfer;
}
public void setbinarytransfer (boolean binarytransfer) {
this.binarytransfer = binarytransfer;
}
public boolean isPassivEmode () {
retornar passiveMode;
}
public void SetpassivEmode (Passivemode booleano) {
this.passivEmode = passiveMode;
}
public String getEncoding () {
Retornar codificação;
}
public void setencoding (codificação de string) {
this.Encoding = coding;
}
public int getClientTimeout () {
return clienttimeout;
}
public void SetClientTimeout (int clientTimeout) {
this.clienttimeout = clienttimeout;
}
public ftpClient (string host) {
this.Username = "Anonymous";
this.Encoding = "UTF-8";
this.binarytransfer = true;
this.binarytransfer = true;
this.port = 21;
this.host = host;
tentar {
this.ftpClient = getftpClient ();
} catch (Exceção e) {
System.out.println ("Crie erro ftpClient!");
}
}
private ftpClient getftpClient () lança ioexception {
FtpClient ftpClient = new ftpClient ();
ftpClient.SetControlEncoding (codificação);
conectar (ftpClient);
if (passiveMode) {
ftpClient.enterlocalPassivEMode ();
}
setFileType (ftpClient);
tentar {
ftpClient.SetSotimeout (clienttimeout);
} catch (SockeTexception e) {
lançar uma nova ioexception ("Defina o erro de tempo limite.", e);
}
retornar ftpClient;
}
private void setFileType (ftpClient ftpClient) lança ioexception {
tentar {
if (binarytransfer) {
ftpClient.SetFileType (ftpClient.binary_file_type);
} outro {
ftpClient.setFileType (ftpClient.ascii_file_type);
}
} catch (ioexception e) {
lançar uma nova ioexception ("não poderia definir o tipo de arquivo.", e);
}
}
public boolean Connect (ftpClient ftpClient) lança ioexception {
tentar {
ftpClient.Connect (host, porta);
int reply = ftpClient.getReplyCode ();
if (ftpreply.ispositiveciction (resposta)) {
if (ftpClient.login (nome de usuário, senha)) {
setFileType (ftpClient);
retornar true;
}
} outro {
this.ftpClient.disconnect ();
lançar uma nova ioexception ("FTP Server recusou a conexão");
}
} catch (ioexception e) {
if (this.ftpclient.isconnected ()) {
tentar {
this.ftpClient.disconnect ();
} catch (ioexception e1) {
lançar uma nova ioexception ("Não foi possível desconectar do servidor.", e);
}
}
lançar uma nova ioexception ("não foi possível conectar ao servidor.", e);
}
retornar falso;
}
private void desconect () lança ioexception {
tentar {
this.ftpClient.logout ();
} catch (ioexception e) {
System.out.println ("Logout pode tempo limite!");
} finalmente {
if (this.ftpclient.isconnected ()) {
this.ftpClient.disconnect ();
}
}
}
public inputStream getStream (String serverfile) lança ioexception {
InputStream unstream = null;
tentar {
Instruam = this.ftpClient.retrievefilestream (serverfile);
System.out.println ("Instruam acabar!");
Retornar o Instream;
} catch (ioexception e) {
System.out.println ("Get Stream Exception");
retornar nulo;
}
}
public boolean writestream (entrada inputStream, string localfile) lança ioexception {
FileOutputStream fout = new FileOutputStream (LocalFile);
int ch = 0;
if (input == null) {
System.out.println ("entrada é nula");
retornar falso;
}
tentar {
ch = input.read ();
while (ch! = -1) {
fout.write (ch);
ch = input.read ();
}
System.out.println ("escreva sobre!");
bandeira de retorno;
} catch (ioexception e) {
lançar uma nova ioexception ("Não foi possível obter arquivo do servidor.", e);
}
}
public boolean isexist (string remotefilepath) lança ioexception {
tentar{
Arquivo de arquivo = novo arquivo (remotefilepath);
String remotepath = remotefilepath.substring (0, (remotefilepath.indexof (file.getName ())-1));
String [] listNames = this.ftpclient.listnames (remotepath);
System.out.println (RemoteFilePath);
for (int i = 0; i <listNames.length; i ++) {
System.out.println (listNames [i]);
if (remotefilepath.equals (listNames [i])) {
bandeira = true;
System.out.println ("arquivo:"+file.getName ()+"existido");
quebrar;
}outro {
bandeira = false;
}
}
} catch (ioexception e) {
lançar uma nova ioexception ("Exceção do arquivo", e);
}
bandeira de retorno;
}
// principal para teste
public static void main (string [] args) lança ioexception {
String hostName = "CP01-Testing-Ps7130.cp01.baidu.com";
String serverfile = "/home/work/check_disk.sh";
String localfile = "/home/work/workspace/project/dhc2-0/dhc/base/ftp/task_get";
FtpClient ftp = novo ftpClient (nome do host);
System.out.println (ftp.isExist (Serverfile));
ftp.WriteStream (ftp.getStream (Serverfile), LocalFile);
ftp.disconnect ();
}
}
Essa ferramenta é usada para upload de cluster com outra ferramenta Hadoop, para que os fluxos de entrada e saída sejam separados, o que também é para facilitar o uso de outra ferramenta.
Para adicionar uma coisa, como executar na configuração do Linux:
Se esse código precisar ser executado no Linux, antes de tudo, você precisa configurar o pacote responsivo, por exemplo
A cópia do código é a seguinte:
importar org.apache.commons.net.ftp.ftpClient;
Este pacote é baixado diretamente no site da Apache.
A cópia do código é a seguinte:
exportar ftppath = "$ {path} /xxx.jar"
javac -classpath $ ClassPath: $ ftppath ftpclient.java
Da mesma forma, o ClassPath deve ser especificado ao executar:
A cópia do código é a seguinte:
Java -Classpath $ Classpath: $ ftppath ftpClient
Recomenda -se não incluir $ ftppath no ClassPath, basta consultar as variáveis de ambiente se você o usar.
O acima é tudo sobre este artigo.
Reserve algum tempo para compartilhar o artigo com seus amigos ou deixar um comentário. Agradecemos sinceramente o seu apoio!