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.
Related
Below is piece of code I have written to FTP a HTML file to a server. Although I get no errors in the code, when I execute the program I get the No Class Def Found Error on the FTPClient. I have downloaded commons-net-3.6-bin and import the following jar file into my project library
commons-net-3.6.jar
commons-net-3.6-source.jar
commons-net-examples-3.6.jar
Not sure where to go from here.
String projectPath = System.getProperty("user.dir");
String ImportSKU = projectPath + "Import SKU.HTML";
File file = new File(ImportSKU);
FTPClient client = new FTPClient();
String filename = ImportSKU;
// Read the file from resources folder.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try (InputStream is = classLoader.getResourceAsStream(filename)) {
client.connect("ftp://www.data.com");
client.login("usedid", "password");
// Store file to server
client.storeFile(filename, is);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
I am trying to create a simple java application that downloads a file from URL, stores the file and then uploads the file to FTP to store it.
I have a (local) working code that downloads the file to my local machine on C:\ and uses the local file to upload to FTP.
I would like to move this application to OpenShift and run it in Tomcat6 from there. This means that I have to change the C:\ drive reference to a directory in OpenShift. I referenced the "tmp" directory.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
public class AppRun {
public static void main(String[] args) {
Logger log = Logger.getLogger(AppRun.class);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String formattedDate = sdf.format(date);
downloadFile(formattedDate);
uploadFile(formattedDate);
}
// FILE DOWNLOAD
public static void downloadFile(String formattedDate){
Logger log = Logger.getLogger(AppRun.class);
String sourceURL = "http://websiteURL/pdf/"+formattedDate+".pdf";
String destinationLocation = "/tmp/"+formattedDate+".pdf";
try {
org.apache.commons.io.FileUtils.copyURLToFile(
new URL(sourceURL),
new File(destinationLocation)
);
log.warn("/tmp/"+formattedDate+".pdf downloaded successfully!" );
}
catch (Exception e) {
log.error(e);
log.error("Source URL : " + "http://websiteURL/pdf/"+formattedDate+".pdf" + " Destination URL : " + "/tmp/"+formattedDate+".pdf");
System.out.println("No file found!");
}
}
// FILE UPLOAD
public static void uploadFile(String formattedDate){
Logger log = Logger.getLogger(AppRun.class);
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.domain.com");
client.login("user", "pass");
// Create an InputStream of the file to be uploaded
String originalFile = "/tmp/"+formattedDate+".pdf";
fis = new FileInputStream(originalFile);
//
// Store file to server
//
String destinationFileName = formattedDate +".pdf";
client.storeFile(destinationFileName, fis);
log.warn("File " + formattedDate +".pdf uploaded successfully!");
client.logout();
} catch (IOException e) {
log.error(e);
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
log.error(e);
e.printStackTrace();
}
}
}
}
When I run the code, I can download the file but the upload part fails:
/var/lib/openshift/XXXXXXXXXXXXXXXXXXXX/app-root/runtime/repo//.openshift/cron/minutely/java:
2015-09-15 22:27:08 WARN AppRun:41 - /tmp/20150915.pdf downloaded
successfully! 2015-09-15 22:27:09 ERROR AppRun:77 -
java.net.BindException: Permission denied java.net.BindException:
Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.(ServerSocket.java:237)
at javax.net.DefaultServerSocketFactory.createServerSocket(ServerSocketFactory.java:231)
at org.apache.commons.net.ftp.FTPClient.openDataConnection(FTPClient.java:797)
at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:633)
at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:624)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1976)
at AppRun.uploadFile(AppRun.java:72)
at AppRun.main(AppRun.java:25)
Any suggestions how to fix this would be greatly appreciated! Thanks.
Configure the client for FTP PASSIVE mode.
Try adding ftp.enterLocalPassiveMode() after login.
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?
I want to get a file from resources folder if it exists and create it there if it doesn't. I want to access it as file. class.getResource() doesn't work as it returns an URL. class.getResourceAsStream() gives input stream, but then I can't write in it or can I somehow?
import java.io.File;
import java.io.FileNotFoundException;
public class Statistika {
File file;
public Statistika() {
try {
file = Statistika.class.getResourceAsStream("statistics.txt");
} catch (FileNotFoundException e) {
file = new File("statistics.txt");
}
}
How to make this work?
Try using Statistika.class.getClassLoader().getResource(filename);If it returns null then you can create new file/directory. If your accessing this from jar then use Statistika.class.getClassLoader().getResourceAsStream(filename);
Hope it will solve your problem. Let me know if you found any difficulties.
Have you tried this?
File f = new File(Statistika.class.getResource("resource.name").toURI());
if (!f.isFile()){
f.getParentFile().mkdirs();
f.createNewFile();
}
Don't do file = new File("statistics.txt"); in your catch block .. just do the following
try {
File file = new File("statistics.txt");
InputStream fis = new FileInputStream(file);
fis = Statistika.class.getResourceAsStream(file.getName());
} catch (FileNotFoundException e) {
}
This is independent of whether the file exists or not.
File f = new File("statistics.txt");
try {
f.createNewFile();
} catch (IOException ex) { }
InputStream fis = new FileInputStream(f);
Use BufferedReader to insert contents to file referenced by f.
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.