I've to upload a zip file to ftp server, And here zip file also constructing dynamically.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
public class CommonsNet {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("127.0.0.1");
client.login("phani", "phani");
String filename = "D://junk.pdf";
fis = new FileInputStream(new File(filename));
byte[] bs = IOUtils.toByteArray(fis);
fis.close();
OutputStream outputStream = client.storeFileStream("remote.zip");
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.setLevel(ZipOutputStream.STORED);
addOneFileToZipArchive(zipOutputStream,
"junk.pdf", bs);
zipOutputStream.close();
outputStream.close();
client.logout();
System.out.println("Transfer done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void addOneFileToZipArchive(ZipOutputStream zipStream,
String fileName, byte[] content) throws Exception {
ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName);
zipStream.putNextEntry(zipEntry);
zipStream.write(content);
zipStream.flush();
zipStream.closeEntry();
}
}
After executing this code the file is successfully created but i am unable to open a file inside archive.
like :
! D:\phani\remote.zip: The archive is corrupt
! D:\phani\remote.zip: Checksum error in C:\Users\BHAVIR~1.KUM\AppData\Local\Temp\Rar$DIa0.489\MCReport.pdf. The file is corrupt
Try adding client.setFileType(FTP.BINARY_FILE_TYPE); just after you have logged in.
I remember that default transfer mode is ASCII, so non-ascii files may result corrupted.
Related
With this code iI always get a empty file.
What I have to do with it?
login is always true. (ofc, here is not real password)
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
public class Logs {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("myac.cs-server.pro", 121);
boolean login = client.login("a3ro", "passWordIsSecret");
System.out.println(login);
String remoteFile1 = "myac_20150304.log";
File downloadFile1 = new File("C:\\Users\\Aero\\Desktop\\test\\myac.log");
OutputStream outputStream1 =
new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = client.retrieveFile(remoteFile1, outputStream1);
System.out.println(success);
outputStream1.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Use FileOutputStream:
String filename = "test.txt";
FileOutputStream fos = new FileOutputStream(filename);
client.retrieveFile("/" + filename, fos);
Use something like this:
InputStream inputStream = client.retrieveFileStream(remoteFileNameHere);
To retrieve the remote file input stream.
Then you can use to copy the stream to desired file:
FileOutputStream out = new FileOutputStream(targetFile);
org.apache.commons.io.IOUtils.copy(in, out);
I'm trying to download a file from server using FTP, the Java code works if the file is available in remote server but if the specific file is not available in the remote server a new file is getting created with same file name in local. How can I avoid this?
and I'm trying to check the properties such as last modified time, file created time etc.., of the specific file before download, I used MLST but getting type casting issues..!!
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPDownloadFileDemo {
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// APPROACH #1: using retrieveFile(String, OutputStream)
String remoteFile1 = "/test/video.mp4";
File downloadFile1 = new File("D:/Downloads/video.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.");
}
outputStream2.close();
inputStream.close();
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
The retrieveFile() method always writes a local file, whether or not the remote file exists. Instead, you can use retrieveFileStream() and check the reply code.
A handy list of FTP reply codes is available from Wikipedia. If 550 is received, it means the file does not exist.
Finally, you need to use completePendingCommand() to complete the transaction and a FileOutputStream to write the file.
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile1);
int returnCode = ftpClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
System.out.println("Remote file does not exist");
} else {
ftpClient.completePendingCommand();
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
OutputStream outputStream = new FileOutputStream(downloadFile1);
outputStream.write(buffer);
outputStream.close();
}
Your problem is that your Outputstream automatically creates the File, even if the stream is empty.
I would recommend you check first if the file exists on the server and based on that you don't even create the outputStream:
boolean checkFileExists(String filePath) throws IOException {
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile1);
returnCode = ftpClient.getReplyCode();
return inputStream == null || returnCode == 550;
}
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol - this is the error i am getting when i run this code:
package ftp.upload;
import java.io.FileInputStream;
import java.io.IOException;
public class FtpUpload {
public static void main(String[] args) {
/* line 14 */ FtpClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("test.info");
client.login("test", "test");
//
// 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();
}
}
}
}
that is the code for my ftp upload the error is on line 14
thanks for the help
Currently your compiler doesn't know what FTPClient is.
Download this commons-net.jar file from here
Add a import to FTPClient
import org.apache.commons.net.ftp.FTPClient;
Also there's a typo on your code,
FtpClient client = new FTPClient();
but it should be
FTPClient client = new FTPClient();
Also have a look at here for FTPClient documentation.
I'm trying to develop a simple Java file transfer application using TCP.
My current server code is as follows:
package tcp.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args) {
new FTPServer().go();
}
void go() {
try {
ServerSocket server = new ServerSocket(2015);
System.out.println("server is running ....!");
while (true) {
Socket socket = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String file = reader.readLine();
System.out.println("file to be downloaded is : " + file);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
//bos.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Using my current server code above, the downlloding does not work as expected. the above code sends part of the file to the client , not the entire file. Note that I used the flush method to flush the buffer. but when I replace the flush () method by the close () method, the file is fully sent to the client whithout any loss. Could anyone please explain this behavior!
UPDATE: Here is the code of my client:
package tcp.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* #author aaa
*/
public class FTPClient {
public static void main(String[] args) {
String file = "JasperReports-Ultimate-Guide-3.pdf";
try {
InetAddress address = InetAddress.getLocalHost();
Socket socket = new Socket(address, 2015);
System.out.println("connection successfully established ....!");
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println(file);
pw.flush();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy" + file));
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
System.out.println("file download is complete ...!");
} catch (UnknownHostException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Another behavior without the use of Socket. take the following code that copy a file from a source to a destination:
public class CopieFile {
static void fastCopy(String source, String destination) {
try {
FileInputStream fis = new FileInputStream(source);
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(destination);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) throws IOException {
String source = "...";
String destination = "...";
fastCopy(source, destination);
}// end main
}// end class
the above code to copy a file from one location to another without any loss. Note well that I did not close the stream.
If you never close the stream the client wil never get end of stream so it will never exit the read loop.
In any case the stream and the socket are about to go out of scope, so if you don't close them you have a resource leak.
I tried this code to download a file from my company's ftp site. The file gets downloaded but has 0 kb in size. Any idea? Thanks a lot !
package org.kodejava.example.commons.net;<br/><br/>
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.FileOutputStream;
public class FtpDownloadDemo {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
String filename = "sitemap.xml";
fos = new FileOutputStream(filename);
client.retrieveFile("/" + filename, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}