I am trying to store a byteArrayInputStream as File on a FTP Server. I could already connect to the Server and change the working path, but triggering the method to store the Stream as File on the Server returns always false.
I am using the apache FTPClient.
Can someone please give me a hint where my mistake can be!?
Here the Code:
String filename = "xyz.xml"
// connection returns true
connectToFtpServer(ftpHost, ftpUser, ftpPassword, exportDirectory);
// byteArray is not void
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
try {
// change returns true
result = ftpClient.changeWorkingDirectory(exportDirectory);
// storing the file returns false
result = ftpClient.storeFile(filename, byteArrayInputStream);
byteArrayInputStream.close();
ftpClient.logout();
} catch (...) {
...
} finally {
// disconnect returns true
disconnectFromFtpServer();
}
I don't believe it's your code. Here is another example that looks very similar from kodejava:
package org.kodejava.example.commons.net;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FileUploadDemo {
public static void main(String[] args) {
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();
}
}
}
}
I agree it's file permissions. There is not a way to change permissions in java itself yet, but there are other solutions. See this thread: How do i programmatically change file permissions?
HTH,
James
It was actually a permission issue due to an invalid usergroup. After adding my user to the usergroup, i was able to store again files.
Related
we are using below code to upload files back to the FTP server?
basically 60 MB file is taking 3 minutes to upload to ftp server.Is there any way to make it faster?Please note that uploadable file(input file) and ftp server, both are on the same host but still its taking this much time.
at this line client.storeFile(filename, fis) its taking maximum time.
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 = "sample.zip";
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();
}
}
How can I edit the content of a file located on the internal storage in my Android app.
I want to erase the whole content and then write to the file again, instead of appending data to the current content.
Here's my code to read and write:
package com.example.cargom;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
public class FileManager {
FileOutputStream outputStream;
FileInputStream inputStream;
public void writeToFile(Context context, String fileName, String data) {
try {
outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readFromFile(Context context, String fileName) {
String data = "";
int c;
try {
inputStream = context.openFileInput(fileName);
while ((c = inputStream.read()) != -1) {
data = data + Character.toString((char) c);
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
Your class is already doing what you rquire. It first erases the contents of the file and then writes on it. For further understanding,
When you initiate your stream with MODE_PRIVATE, the second time when you try to write the file, the contents that are already in the file gets erased and the new contents are written.
outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
When you use MODE_APPEND, the contents that are already there stays and the new contents will be appended to the file.
outputStream = context.openFileOutput(fileName, Context.MODE_APPEND);
For more reference and detailed knowledge on dealing with files in Internal storage, I recommend you to watch the below three short videos which gives you detailed description with demo.
http://www.youtube.com/watch?v=Jswr6tkv8ro&index=4&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
http://www.youtube.com/watch?v=cGxHphBjTBk&index=5&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
http://www.youtube.com/watch?v=mMcrj_To18k&index=6&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
Hope it helps! Any more questions, please comment below.
You can just delete the file first with:
File f = new File(filename);
if(f.exists()){
f.delete();
}
And then create a new one with same path/name and write to it.
I'm assuming that your filename is the path to the file on the device.
But probably I'm not getting your real problem?
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 have used this code
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FTPClientExample {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("hostname");
client.login("user", "pwd");
String filename = "D:\\Task\\try.txt";
fis = new FileInputStream(filename);
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();
}
}
}
}
when i run this,i get the message task complete.But i couldnt find out which folder i should look for the file.some one pls help me?
you are trying to upload on the path D:\\Task\\try.txt .I guess that is your source file path.
You should write something like
client.storeFile(ftpPath + filename, fis);
where ftpPath should be the FTP server location where you want to upload the file.
Edit:: File path structure
ftp://"+username+":"+password+"#"+ip+"/"+dir+"/"+fileName
OK change
String filename = "D:\\Task\\try.txt";
to String filename = "/home/user_name/Desktop";where user_name is your user name for linux .. give it a try the file should be on your Desktop and remember linux is case sensitive.
In case of linux the path String filename = "D:\\Task\\try.txt"; changes to String filename = "/media/your_drive_name/try.txt";
here is linux directory structure explained.
My code is,
import java.io.*;
import java.net.*;
public class DownloadHttp
{
public static void main(String a[])
{
DownloadHttp d = new DownloadHttp();
String addr = "http://www.gmail.com";
String file = "D:/venkatesh/Software/download1.html";
d.download(addr,file);
}
public void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
}
}
Here I wants download specific file using httpClient using java.
It produces:
"java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)" as error.
How to resolve it, help me, thanks in advance.
I believe it is a network problem. Have you tried to access the url directly or are you behind a firewall?
Recompiled your code on my machine, it works perfectly well. I'm able to fetch files from the web.
Check if your web-browser can download the file for you (make sure it's not a network problem)
One thing to notice though, in your finally block you might want to close the streams separately. So if anything goes wrong with the input stream, the output stream will still be closed.
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ignored) {}
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {}
}
I think you are using a proxy when connecting to internet.
Set these in the code and then retry.
System.setProperty("http.proxyHost", *Proxy-IP*);
System.setProperty("http.proxyPort", *Proxy-Port*);