Get garbage value in file while downloading from ftp - java

I tried to download csv file from ftp .
File is downloaded successfully but it gives me garbage value in that file.
Following is my code
String server = "client.in";
int port = 21;
String user = "user";
String pass = "pwd";
InputStream input=null;
BufferedWriter out = null;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileOutputStream fos = null;
String filename = "Test.csv";
OutputStream data = (OutputStream) new FileOutputStream("Test/"+filename);
ftpClient.retrieveFile(filename, data);
data.close();
}
catch(Exception e)
{
e.printStackTrace();
}
What is the solution ....
please help

Related

How to get path of the file on Server using Java Code?

I have uploaded a file on server 'www.server.com'. Now I wish to know the path of the file on the same server through java code. Is there any specific method or process present? I am new to this.
public class Test {
public static void main(String[] args) {
test test = new test();
String server ="www.server.com";
int port = 21;
String username = "abc";
String password = "abc`enter code here`";
FTPClient ftpclient = new FTPClient();
try {
ftpclient.connect(server, port);
ftpclient.login(username, password);
ftpclient.enterLocalPassiveMode();
ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
File firstLocalFile = new File("D:\\ADF\\Tax Files\\TERData.zip");
String firstRemoteFile = "TERData.zip";
InputStream inputstream = new FileInputStream(firstLocalFile);
System.out.println("Start Uploading the First File");
System.out.println(" File Path ":+firstLocalFile.getAbsolutePath());
boolean done = ftpclient.storeFile(firstRemoteFile, inputstream);
if(done){
System.out.println(" File successfully uploaded ");
}
} catch (IOException e) {
// TODO: Add catch code
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FTPFile[] files1 = ftpClient.listFiles("/test");//"/test/test.txt";
String remoteFile1 =files1[0].getName();
File downloadFile1 = new File("D:/Downloads/test.mp4");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
System.out.println("File #1 has been downloaded successfully.");
}

Changes made to .properties file do not reflect in java

I have written a TCP Client program which calls the properties file and takes the values from there. When I run the TCPClient for the first time, it runs properly and sends all the data values of server.properties file to the server, but as soon as I try to add one more data "data4" to server.properties file my project gets a "x" mark and the changes made in server.properties file don't reflect and I get Error: cannot find or load class TCPClient.
I tried to create a new project, still the same, the changes made to properties file do not reflect. Can someone kindly help me on this. Thanks in advance
public class TCPClient {
private static Socket socket;
public String getPropertyValues() throws IOException{
String result="";
Properties prop = new Properties();
String propFileName = "server.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(inputStream);
try
{
String host = prop.getProperty("host");
System.out.println(host);
int port = Integer.parseInt(prop.getProperty("port"));
System.out.println(port);
String data = prop.getProperty("data");
System.out.println(data);
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String sendMessage = data;
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) throws IOException{
TCPClient properties = new TCPClient();
properties.getPropertyValues();
}
}
I have a properties file by name server.properties
data = data1
data2
data3
port = 3035
host = localhost
When ever I make change to the data field of this properties file and save, the project turns with a "x" mark and when I try to run the TCPClient program using Run as-->JavaApplication, I get the pop up as
Errors exist in required project
Test
Proceed with Launch?

Java why java ftp uploads file corrupted

I'm trying to upload image to my server but when I'm trying to open this image - it's not possible to open, apparently because it's corrupted. Can someone help me and tell me why? thanks!
I'm using the Apache Commons Net jar.
String hostName = "host";
String username = "username";
String password = "pass";
String location = "filePath.png";
FTPClient ftp = null;
InputStream in = null;
try {
ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.changeWorkingDirectory("/pictures");
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if(FTPReply.isPositiveCompletion(reply))
{
System.out.println("Connected Success");
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
File f1 = new File(location);
in = new FileInputStream(f1);
ftp.storeFile("fileName.png",in);
System.out.println("SUCCESS");
in.close();
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
My antivirus was blocking it..

Error in uploaing file from android to ftp server

I'm trying to upload an image from android to ftp server, but when i try to open the image that i uploaded i see the following message instead of the image "the image cannot be displayed because it contains errors"
and this is the code that i use
public void uploadImage(String path){
String server = "www.domainname.com";
int port = 21;
String user = "ftp-username";
String pass = "ftp-password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// APPROACH #1: uploads first file using an InputStream
File firstLocalFile = new File(path);
long fileSize = firstLocalFile.length();
Log.i("File Size",fileSize+"");
String firstRemoteFile = "testfile1.jpg";
InputStream inputStream = new FileInputStream(firstLocalFile);
Log.i("uploading", "Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
Log.i("uploaded", "finished uploading first file");
}
// APPROACH #2: uploads second file using an OutputStream
File secondLocalFile = new File(path);
String secondRemoteFile = "testfile2.jpg";
inputStream = new FileInputStream(secondLocalFile);
Log.i("uploading", "Start uploading second file");
OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
if (completed) {
Log.i("uploaded", "finished uploading second file");
}
} catch (IOException ex) {
Log.i("Error", "Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
where is the error!!?
Thanks in advance..
This looks suspiciously like this bug: FTPClient corrupts the images while uploading to ftp server on android?
Try using FTP4J instead.

How do you upload a file to an FTP server?

I created a function to download files from an FTP server that I have access to. How would I upload files back to the FTP server?
Below is the download_files method i used:
public static void download_files(String un, String pw, String ip, String dir, String fn, String fp){
URLConnection con;
BufferedInputStream in = null;
FileOutputStream out = null;
try{
URL url = new URL("ftp://"+un+":"+pw+"#"+ip+"/"+dir+"/"+fn+";type=i");
con = url.openConnection();
in = new BufferedInputStream(con.getInputStream());
out = new FileOutputStream(fp+fn);
int i = 0;
byte[] bytesIn = new byte[1024];
while ((i = in.read(bytesIn)) >= 0) {
out.write(bytesIn, 0, i);
}
}catch(Exception e){
System.out.print(e);
e.printStackTrace();
System.out.println("Error while FTP'ing "+fn);
}finally{
try{
out.close();
in.close();
}catch(IOException e){
e.printStackTrace();
System.out.println("Error while closing FTP connection");
}
}
}
Use the FTPClient Class from the Apache Commons Net library.
This is a snippet with an example:
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// Create an InputStream of the file to be uploaded
//
String filename = "Touch.dat";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
Snippet taken from http://www.kodejava.org/examples/356.html
I have used the EDT FTP package, a free GPL library for FTP in Java: http://www.enterprisedt.com/products/edtftpj/overview.html
Here is a code sample, from the Demo.java class they provide:
ftp = new FTPClient();
ftp.setRemoteHost("hostname");
// connect
ftp.connect();
// login
ftp.login("user", "password");
// set up passive ASCII transfers
ftp.setConnectMode(FTPConnectMode.PASV);
ftp.setType(FTPTransferType.ASCII);
// get directory and print it to console
String[] files = ftp.dir(".", true);
for (int i = 0; i < files.length; i++)
log.debug(files[i]);
// copy file to server
ftp.put("test.txt", "test.txt");
// copy file from server
ftp.get("test.txt" + ".copy", "test.txt");
// delete file from server
ftp.delete("test.txt");
// Shut down client
ftp.quit();
Check out FTP4J as well...
Take a look at apache-commons-net they have a some FTP tools which may help you out!

Categories