I am working on File Upload using Java API.
I want to upload file into server by using FTPS , I found that I can use Google library of apache commons net but I am facing issue in org.apache.commons.net.ftp.FTPSClient when i upload file.
Following is the error
Exception in thread "main" java.lang.NullPointerException
this is my code :
public static void main(String[] args) {
String server = "HOST";
int port = 21;
String user = "USER";
String pass = "PASS";
FTPSClient ftpClient;
try {
ftpClient = new FTPSClient();
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("TEST1.CSV");
String firstRemoteFile = "TEST1.txt";
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.");
}
// APPROACH #2: uploads second file using an OutputStream
File secondLocalFile = new File("TEST2.CSV");
String secondRemoteFile = "TEST2.TXT";
inputStream = new FileInputStream(secondLocalFile);
System.out.println("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) {
System.out.println("The second file is uploaded successfully.");
}
} 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();
}
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any support is appreciated
Related
I am trying to unzip files in the FTP location, but when i unzip i am not able to get all the files in FTP server, but when i try the code to unzip files to local machine it is working. I am sure somewhere while writing the data to FTP i am missing something.Below is my code. Please help me on this.
public void unzipFile(String inputFilePath, String outputFilePath) throws SocketException, IOException {
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
InputStream in = null;
FTPClient ftpClientinput = new FTPClient();
FTPClient ftpClientoutput = new FTPClient();
String ftpUrl = "ftp://%s:%s#%s/%s;type=i";
ftpClientinput.connect(server, port);
ftpClientinput.login(user, pass);
ftpClientinput.enterLocalPassiveMode();
ftpClientinput.setFileType(FTP.BINARY_FILE_TYPE);
String uploadPath = "path";
ftpClientoutput.connect(server, port);
ftpClientoutput.login(user, pass);
ftpClientoutput.enterLocalPassiveMode();
ftpClientoutput.setFileType(FTP.BINARY_FILE_TYPE);
try {
// fis = new FileInputStream(inputFilePath);
String inputFile = "/Srikanth/RecordatiFRA_expenses.zip";
String outputFile = "/Srikanth/FR/";
in = ftpClientinput.retrieveFileStream(inputFile);
zipIs = new ZipInputStream(new BufferedInputStream(in));
while ((zEntry = zipIs.getNextEntry()) != null) {
try {
byte[] buffer = new byte[4 * 8192];
FileOutputStream fos = null;
OutputStream out = null;
// String opFilePath = outputFilePath + zEntry.getName();
String FTPFilePath = outputFile + zEntry.getName();
// System.out.println("Extracting file to "+opFilePath);
System.out.println("Extracting file to " + FTPFilePath);
// fos = new FileOutputStream(opFilePath);
out = ftpClientoutput.storeFileStream(FTPFilePath);
// System.out.println(out);
int size;
while ((size = zipIs.read(buffer, 0, buffer.length)) != -1) {
// fos.write(buffer, 0 , size);
out.write(buffer, 0, size);
}
// fos.flush();
// fos.close();
} catch (Exception ex) {
ex.getMessage();
}
}
zipIs.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (ftpClientinput.isConnected()) {
ftpClientinput.logout();
ftpClientinput.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This method will do what you want, you can tweak it as you like.
I cleaned up and removed a lot that you didn't need; One thing to note is the use of try-with-resources blocks and not declaring your local variables so far from where they're used.
Your main error was that you needed to call completePendingCommand after certain methods as noted in their documentation.
Remember to read the documentation on methods you're using for the first time.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public static void unzipFTP(String server, int port, String user, String pass, String ftpPath)
throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect(server, port);
ftp.login(user, pass);
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
try (InputStream ftpIn = ftp.retrieveFileStream(ftpPath);
ZipInputStream zipIn = new ZipInputStream(ftpIn);) {
// complete and verify the retrieve
if (!ftp.completePendingCommand()) {
throw new IOException(ftp.getReplyString());
}
// make the output un-zipped directory, should be unique sibling of the target zip
String outDir = ftpPath + "-" + System.currentTimeMillis() + "/";
ftp.makeDirectory(outDir);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new IOException(ftp.getReplyString());
}
// write the un-zipped entries
ZipEntry zEntry;
while ((zEntry = zipIn.getNextEntry()) != null) {
try (OutputStream out = ftp.storeFileStream(outDir + zEntry.getName());) {
zipIn.transferTo(out);
}
if (!ftp.completePendingCommand()) {
throw new IOException(ftp.getReplyString());
}
}
} finally {
try {
if (ftp.isConnected()) {
ftp.logout();
ftp.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I have this code:
public void uploadToFTP(File file) {
try {
final ByteArrayInputStream stream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
String date = dateFormat.format(new Date());
String filename = date.replaceAll(":", "-");
sessionFactory.getSession().write(stream, "dir/" + filename + ".txt");
} catch (IOException e) {
e.printStackTrace();
}
}
The parameter I got in this case File I want to upload to some FTP, but the problem each time I do this the file actually is empty. When I try for example final ByteArrayInputStream stream = new ByteArrayInputStream("Text here".getBytes()); it is working fine, and stores the information inside the file, what could be the problem here, may I have problem maybe with converting the File to bytes or ?
Use thsi code :
public List<ProcessedFile> uploadFTPFilesByCridational(List<ProcessedFile> processedFiles, String sourceDir,
String destinationPath, String hostName, String userName, String password, String portNo, String extation,
int fileHours, int fileMint) {
List<ProcessedFile> processedFilesList = new ArrayList<>();
try {
FTPClient ftpClient = new FTPClient();
// client FTP connection
ftpClient = connectToFTPClient(hostName, userName, password, portNo);
// check if FTP client is connected or not
if (ftpClient.isConnected()) {
if (processedFiles != null && processedFiles.size() > 0) {
for (ProcessedFile processedFile : processedFiles) {
FileInputStream inputStream = null;
try {
File file = new File(sourceDir + "/" + processedFile.getOriginalFileName());
inputStream = new FileInputStream(file);
if (!ftpClient.isConnected()) {
ftpClient = connectToFTPClient(hostName, userName, password, portNo);
}
ByteArrayInputStream in = null;
try {
ftpClient.changeWorkingDirectory(destinationPath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
in = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
ftpClient.storeFile(file.getName(), in);
} catch (Exception e) {
logger.error(e.getMessage());
}
inputStream.close();
in.close();
processedFile.setProcessedStatus(ProcessedStatus.COMPLETED);
processedFilesList.add(processedFile);
} catch (Exception e) {
logger.error(e);
processedFile.setProcessedStatus(ProcessedStatus.FAILED);
processedFilesList.add(processedFile);
}
}
}
}
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
try {
ftpClient.disconnect();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
} catch (Exception e) {
logger.error("FTP not connected exception: " + e);
}
return processedFilesList;
}
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.
I am trying to write the server client file transfer program in java.
Role of Server:-
a) Serve a file to a client (one).
b) Server will send file 1 byte at a time.
c) Should be able to send the file more than once.
Role of Client:-
a) Client downloads a file
b) Client should buffer the file before writing to disk( <= 100kb) I.e. buffer 100KB and write to disk then repeat this till 1MB
I wrote the code to transfer the file from Server to Client but there seem to have some issues with the program. Server starts sending the data but its lost in the transaction. Also the content of file to be transferred is erased. As I couldn't see any specific error on console so I couldn't figure out the bug. If anyone guide me whether this approach is correct or if not, please suggest proper changes.
*Server*
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
int sizeBuffer = 0;
try{
try {
serverSocket = new ServerSocket(55555);
} catch (IOException ex) {
System.out.println("Error: Unable to Connect to Server ");
}
System.out.println("Created Socket");
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Error: Unable to connect to client ");
}
System.out.println("Accepted Client Connection ");
try {
inputStream = socket.getInputStream();
sizeBuffer = socket.getReceiveBufferSize();
System.out.println("Size of Buffer " + sizeBuffer);
} catch (IOException ex) {
System.out.println("Error: unable to ger socket input stream ");
}
try {
fileOutputStream = new FileOutputStream("D:/ServerFile.txt");
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[sizeBuffer];
int count;
while ((count = inputStream.read(bytes)) > 0) {
bufferedOutputStream.write(bytes, 0, count);
}
System.out.println("Done");
}// end of first try
finally{
bufferedOutputStream.flush();
bufferedOutputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
}
And here is client side code !
*Client*
public class Client {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOuptputStream = null;
Socket socket = null;
int count;
try{
try {
socket = new Socket("127.0.0.1", 55555);
} catch (IOException ex) {
System.out.println("Error: Unable to create Socket ");
}
File file = new File("D:/ClientFile.txt");
long fileLength = file.length();
System.out.println(fileLength);
if ( Integer.MAX_VALUE < fileLength ) {
System.out.println("Error: Exceeded the size of transfer");
}
byte[] bytes = new byte[(int) fileLength];
try{
fileInputStream = new FileInputStream(file);
}catch (IOException ex){
System.out.println("Error: Unable to open fileInputStream");
}
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedOuptputStream = new BufferedOutputStream(socket.getOutputStream());
while ((count = bufferedInputStream.read(bytes)) > 0) {
bufferedOuptputStream.write(bytes, 0, count);
}
}
finally{
bufferedOuptputStream.flush();
bufferedOuptputStream.close();
fileInputStream.close();
bufferedInputStream.close();
socket.close();
}
}
}
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!