I am trying to download the files from ftp server using java FTPClient and FTPFile classes(commons-net.jar).How do i conclude if the file is partial or full(i.e., file is completely uploaded or not) using those classes?
Probably you could use the storeFile method form the Apache FTPClient:
public boolean storeFile(String remote, InputStream local)
throws IOException
Stores a file on the server using the given name and taking input from
the given InputStream. This method does NOT close the given
InputStream. If the current file type is ASCII, line separators in the
file are transparently converted to the NETASCII format (i.e., you
should not attempt to create a special InputStream to do this).
Parameters:
remote - The name to give the remote file. local - The
local - InputStream from which to read the file.
Returns: True if successfully completed, false if not.
Please note the following link Apache FTPClient for more information.
A simple implementation that you could try, would be something like this:
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("D:/Test/Projects.zip");
String firstRemoteFile = "Projects.zip";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println("The first file is uploaded successfully.");
}
...
}
Regards.
Related
I want to add my file to a specific directory ,not root directory in my ftp server.
what can I do ? here is my java code :
FTPClient client = new FTPClient();
String filename = "out.txt";
// Read the file from resources folder.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream(filename);
try {
client.connect("18.14.18.17");
boolean login = client.login("root", "root");
if (login) {
System.out.println("Login success...");
// Store file to server
client.storeFile(filename, is);
client.logout();
}
this code adds the file to my root directory in my ftp server.
I can use method client.changeWorkingDirectory("server directory").
I made a HTML server using com.sun.net.httpserver library. I want to send a jar file to the client to make them download it.
This method below actually make the client download the file:
#Override
public void handle(HttpExchange httpExchange) {
File file = new File("Test.jar");
try {
httpExchange.sendResponseHeaders(200, file.length());
OutputStream outputStream = httpExchange.getResponseBody();
Files.copy(file.toPath(), outputStream);
outputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
but it sends the jar file as a zip. How do I get it to send it as a jar file instead? And is there a better way to send files?
Please try adding the following to get correct filename for the download:
httpExchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=Test.jar");
You might also want do add the following to get the corrent content-type:
httpExchange.setAttribute(HTTPExchange.HeaderFields.Content_Type.toString(), "application/java-archive");
Please see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a listing of content-types for different suffixes.
I'm writing code to read a file from an FTP URL in order to parse it and store the data in Google App Engine's Datastore. I'm able to get the code working fine when reading test files hosted on my own web server, however when I try to read the data file I need I'm getting a FileNotFoundException.
I'm able to use the same FTP URL in a browser to download the file, and can anonymously connect to the FTP URL in FileZilla, so access shouldn't be a problem, and the file is definitely there. It's a pretty big file, but I've tried to grab smaller files from the same FTP server with no luck either.
Here's the code I have at the moment:
public void doGet(HttpServletRequest req,
HttpServletResponse resp) throws IOException, ServletException {
// works with a URL to my own server & a test.zip, but not this one
final URL url = new URL(
"ftp://gisftp.metc.state.mn.us/google_transit.zip");
// without the privileged action, I get an AccessControlException
ZipInputStream zin = AccessController.doPrivileged(
new PrivilegedAction<ZipInputStream>() {
public ZipInputStream run() {
return getZipStream(url);
}
}
);
ZipEntry zipentry = zin.getNextEntry();
// processing files here
zin.close();
}
// but using the privileged method, we get a FileNotFoundException
public ZipInputStream getZipStream(URL url) {
ZipInputStream zipin = null;
try {
zipin = new ZipInputStream(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
return zipin;
}
At first I was getting an AccessControlException, but using a PrivilegedAction to open the stream seems to fix that.
I don't have access to the server where the file is stored, so can't change anything there.
I think there is a restriction on the ports that can be connected to from App Engine and FTP (21) is not in the list, this maybe causing the issue. From the URL Fetch documentation;
An app can fetch a URL using HTTP (normal) or HTTPS (secure). The URL specifies the scheme to use: http://... or https://...
The URL to be fetched can use any port number in the following ranges: 80-90, 440-450, 1024-65535. If the port is not mentioned in the URL, the port is implied by the scheme: http://... is port 80, https://... is port 443.
if I have a ftp server at ftp://ftpdomainname.com and I want to upload file to it, how do I check for its permissions using Commons Net ?
I try:
ftpClient = new FTPClient();
ftpClient.connect(url.getHost());
ftpClient.login(username, pass);
FTPFile[] directories = mFtpClient.listDirectories("/");
for(FTPFile dir : directories) {
permissions = dir.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION);
}
but it's not getting the permissions for the root server (folder) but for its subfolders.
Can i specify url like ftp://ftpdomainname.com/ and get whether I have write permissions? Or url like ftp://ftpdomainname.com/subfolder1/subfolder2/ ?
Thanks
Using Commons Net 3.1 FTPClient class, you could try obtaining current FTPFile by issuing the following command
FTPFile current = mFTPClient.listFiles(".")[0];
// Then check permissions as your upper code does.
As, after all, on most hosts, the current file can be accessed through ".".
EDIT some clarifications according to comment.
Suppose you just connected to your FTP server (before to try to upload file) :
ftpClient = new FTPClient();
ftpClient.connect(url.getHost());
ftpClient.login(username, pass);
Once it is done, immediatly try to get access to current folder (which should be your default user folder, in other words the folder where you want to upload your file) :
FTPFile current = mFTPClient.listFiles(".")[0];
In this folder, read permissions, and you'll have permissions for your root folder :
current.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION);
Want to write something ? Then check the WRITE_PERMISSION.
I want to write to a remote file as well as read the contents of a remote file. My string is like http://www.mywebsite.info/other/poll.txt . How to convert this string into URL/URI ? My goal is to write as well as read the contents of the file hosted on my server. (via applet)
Can i use FileReader and FileWriter for this ?
FileReader and FileWriter are used to read and write files from/to the file system.
An applet communicates with its origin server using HTTP. And HTTP isn't a protocol used to read and write files. To read it, you need to open a HttpUrlConnection to this URL. To write it, you'll need to have some server component (a PHP application, a Servlet, whatever) and send an appropriate request to this server component so that it writes to the file.
Read up on how HTTP works before trying to write your applet.
Try something like this for reading -
try {
URL url = new URL("http://www.mywebsite.info/other/poll.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (MalformedURLException e) {
// do something meaningful here when the exception is caught
} catch (IOException e) {
// do something meaningful here when the exception is caught
}