Hi I'm trying to get my program to download a text document from my FTP server.
This is the code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
public class NetTestFTP {
public static void main(String[] args) {
FTPClient client = new FTPClient();
OutputStream outStream;
try {
client.connect("82.44.221.198");
client.login("User", "Pass");
String remoteFile = "/hello.txt";
outStream = new FileOutputStream("hello.txt");
client.retrieveFile(remoteFile, outStream);
} catch (IOException ioe) {
System.out.println("Error communicating with FTP server.");
} finally {
try {
client.disconnect();
} catch (IOException e) {
System.out.println("Problem disconnecting from FTP server");
}
}
}
}
Related
I have a problem, that when I create 2 files (Client.java and Server.java) on the same PC, it works. But when I send the Client.java file to another PC, it doesn't work. I also turn off fire wall but it still doesn't work.
Class Sever.java:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
try {
System.out.println("loading..");
ServerSocket serverSocket = new ServerSocket(6667);
Socket socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
String str = dataInputStream.readUTF();
System.out.println(str);
dataInputStream.close();
socket.close();
System.out.println("end");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Class Client.java:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
System.out.println("client connecting...");
byte[] addr = {(byte) 192, (byte) 168, (byte) 9, (byte) 9};
InetAddress inetAddress = InetAddress.getByAddress("lvh", addr);
Socket socket = new Socket(inetAddress, 6667);
//socket.setSoTimeout(999999999);
System.out.println(socket.isConnected());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF("hello");
dataOutputStream.flush();
dataOutputStream.close();
socket.close();
System.out.println("end");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I send class Client.java to other PC and get error "Connection timed out" like this picture (T_T):
enter image description here
I don't how to fix :(( help plz!!!
You need to open DataOutputStream in both ends before you open DataInputStream.
UPDATE: added code
Server.java
package src;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
try {
System.out.println("loading..");
ServerSocket serverSocket = new ServerSocket(6667);
try (Socket socket = serverSocket.accept()) {
try (DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
try (DataInputStream dataInputStream = new DataInputStream(socket.getInputStream())) {
String str = dataInputStream.readUTF();
System.out.println(str);
}
}
}
System.out.println("end");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Client.java
package src;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
System.out.println("client connecting...");
byte[] addr = {(byte) 127, (byte) 0, (byte) 0, (byte) 1};
InetAddress inetAddress = InetAddress.getByAddress("localhost", addr);
try (Socket socket = new Socket(inetAddress, 6667)) {
//socket.setSoTimeout(999999999);
System.out.println(socket.isConnected());
try (DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
try (DataInputStream dataInputStream = new DataInputStream(socket.getInputStream())) {
dataOutputStream.writeUTF("hello");
}
}
}
System.out.println("end");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server Output
loading..
hello
end
Client Output:
client connecting...
true
end
Hope this helps. :)
i got some struggle with my code. I have to send some commands via client to a server (create a file or list files in the directory) the server should create the files or send a list of existing files back to the client. It worked, but i guess the while loop for output on client side never stops and the client cant input new commands. I dont get the problem :(. Many thanks in advance.
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
public class MyServer {
private final static String DIRECTORYLISTING = "directoryListing";
private final static String ADDFILE = "addFile";
private static String path = "/home/christoph/eclipse-workspace/Distributed Systems Ex 01/Work_Folder";
private static PrintWriter pw = null;
private static File file = null;
private static String command1 = null; // Command
private static String command2 = null; // File name
private static String command3 = null; // File content
private static ArrayList<File> files = new ArrayList<>(); //
public static void splitClientInput(String clientInput) {
try {
String [] splittedInput = clientInput.split(";");
command1=splittedInput[0];
command2=splittedInput[1];
command3=splittedInput[2];
} catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public static void directoryListing() {
try {
File[] s = file.listFiles();
for(int i = 0; i<s.length;i++) {
pw.println(s[i].getName());
}
pw.flush();
}catch(NullPointerException e) {
e.printStackTrace();
}
}
public static void addFile(String command2,String command3) throws IOException {
file = new File(path +"/" +command2);
if(file.isFile()) {
pw.println("This Filename "+command2+" already exists.");
} else {
try {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(command3);
files.add(file);
pw.println(file.getName()+" created");
if(command3.equals(null)) {
pw.println("Your created file is empty");
}
fileWriter.close();
}catch(IOException e) {
pw.println("Error by creating file");
}catch (NullPointerException e) {
pw.println("Your created file is empty");
}
}
}
public static void checkInputCommand(String command1, String command2, String command3) throws IOException {
switch(command1) {
case DIRECTORYLISTING:
directoryListing();
break;
case ADDFILE:
addFile(command2, command3);
break;
}
}
public static void main(String[] args) {
try {
file = new File(path);
files = new ArrayList<File>(Arrays.asList(file.listFiles()));
ServerSocket ss = new ServerSocket(1118);
System.out.println("Server Started...");
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
pw=new PrintWriter(os);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String clientInput = null;
while((clientInput = br.readLine()) != null) {
splitClientInput(clientInput);
checkInputCommand(command1, command2, command3);
pw.flush();
}
pw.flush();
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
ss.close();
System.out.println("Server closed");
}catch(BindException e) {
e.printStackTrace();
}catch(SocketException e) {
e.printStackTrace();
}catch(java.lang.NullPointerException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MyClient {
public static void main(String[] args) throws Exception{
try {
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1118);
System.out.println("Client started");
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String str= null;
while(true){
System.out.print("Client input: ");
pw.println(sc.nextLine());
pw.flush();
// System.out.println(br.readLine());
/*
* dont get out of the loop?
*/
while((str=br.readLine())!=null) {
System.out.println(str);
}
br.close();
isr.close();
is.close();
s.close();
}
} catch(NullPointerException e) {
e.printStackTrace();
} catch(ConnectException e) {
e.printStackTrace();
}catch(UnknownHostException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Hello Every one i am working one project where i need to upload file on my ftp server with my java standalone application
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class Ftpdemo {
public static void main(String args[]) {
// get an ftpClient object
FTPClient ftpClient = new FTPClient();
ftpClient.setConnectTimeout(300);
FileInputStream inputStream = null;
try {
// pass directory path on server to connect
ftpClient.connect("ftp.mydomain.in");
// pass username and password, returned true if authentication is
// successful
boolean login = ftpClient.login("myusername", "mypassword");
if (login) {
System.out.println("Connection established...");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
inputStream = new FileInputStream("/home/simmant/Desktop/mypic.png");
boolean uploaded = ftpClient.storeFile("user_screens/test3.png",inputStream);
if (uploaded) {
System.out.println("File uploaded successfully !");
} else {
System.out.println("Error in uploading file !");
}
// logout the user, returned true if logout successfully
boolean logout = ftpClient.logout();
if (logout) {
System.out.println("Connection close...");
}
} else {
System.out.println("Connection fail...");
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
its working fine for the data which is 1 or 2 kb but when i try to upload the file which is of 50 kb and 100 kb then it not working fine. The image uploaded on the server is blank .
As far as I can see, there is nothing wrong with the code. As you're saying 1 or 2 kb of data uploading works fine. So, In my opinion, there is problem with your internet. Might be it's too slow to upload a file size of 50 kb or more.
There is noting wrong with your code only issue with the file or internet speed.Code is working fine here and Also there is recommended that NOT TO USE FTP DETAILS DIRECTLY please avoid this stuff from application you have better option to use web service for your server related stuff.
Good Luck
It seems you had not made connection Instances properly.
Please refer my working code:
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader() throws Exception {
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(new FileOutputStream("c:\\ftp.log"))));
int reply;
ftp.connect(Constant.FTP_HOST);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception(Constant.FTP_SERVER_EXCEPTION);
}
ftp.login(CommonConstant.FTP_USERNAME, Constant.FTP_PASSWORD);
ftp.setFileType(FTP.TELNET_TEXT_FORMAT);
ftp.enterLocalPassiveMode();
}
public boolean uploadFile(File localFileFullName, String fileName) throws Exception {
InputStream input = new FileInputStream(localFileFullName);
boolean reply = this.ftp.storeFile("'" + fileName +"'", input);
disconnect();
return reply;
}
public void disconnect() {
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException e) {
System.out.println(this.getClass()+ e);
}
}
}
public static void main(String[] args) throws Exception {
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader();
System.out.println(ftpUploader.uploadFile(new File("C:\\test.txt"), "Destinate_DIR"));
System.out.println("Done");
}
}
All the best ...!!!
I'm getting this error (550 the filename, directory name, or volume label syntax is incorrect. )
I think the url is correct (obviously not though). Any thoughts?
Here is the url:
STOR /images/report/6F81CB22-3D04-4BA3-AC3F-3D34663449E0**9.png
Here is the invocation method:
private void uploadImageToFtp(String location, String imageName) throws Exception{
File imageFile = new File(location);
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader("ftp.xxx.com", "user", "password");
ftpUploader.uploadFile(imageFile, imageName, "/images/report/");
imageFile.delete();
ftpUploader.disconnect();
System.out.println("Done");
}
Here is the
ftp class:
package server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader(String host, String user, String pwd) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
public void uploadFile(File file, String fileName, String hostDir)
throws Exception {
try {
InputStream input = new FileInputStream(file);
this.ftp.storeFile(hostDir + fileName, input);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void disconnect(){
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// do nothing as file is already saved to server
f.printStackTrace();
}
}
}
}
If the FTP server is running Windows, the '*' characters are the problem. Windows file names may not have asterisks.
Try changing working directory first before uploading
ftp.changeWorkingDirectory(DESTPATH);
It worked for me.
I'm trying to send one object from the server side socket to the client side socket over TCP. I can't find out where is the problem.
Here is the error I'm getting on the Client side:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at ClientSide.main(ClientSide.java:16)
Code for Server side:
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class ServerSide {
public static void main(String[] args) {
try
{
ServerSocket myServerSocket = new ServerSocket(9999);
Socket skt = myServerSocket.accept();
ArrayList<String> my = new ArrayList<String>();
my.set(0,"Bernard");
my.set(1, "Grey");
try
{
ObjectOutputStream objectOutput = new ObjectOutputStream(skt.getOutputStream());
objectOutput.writeObject(my);
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Code for the Client Side:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class ClientSide {
public static void main(String[] args)
{
try {
Socket socket = new Socket("10.1.1.2",9999);
ArrayList<String> titleList = new ArrayList<String>();
try {
ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream()); //Error Line!
try {
Object object = objectInput.readObject();
titleList = (ArrayList<String>) object;
System.out.println(titleList.get(1));
} catch (ClassNotFoundException e) {
System.out.println("The title list has not come from the server");
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("The socket for reading the object has problem");
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Changing from set to add does the trick
ArrayList<String> my = new ArrayList<String>();
my.add("Bernard");
my.add("Grey");
ps. as advised by the others this is not a good idea but, use only for learning