I am able to connect Ftp server. My requirement is to check if the path that will be shown after login into the server is writable in the ftp server.
Below code is not checking File remotefile = new File(pwd)
public StringBuffer verifyMath(String host, String uname, String password, String cType){
String MathString = "FTPHost:[" + host + "];uname[" + uname + "];cType[" + cType + "]";
StringBuffer mBuffer = new StringBuffer();
FileInputStream fis = null;
FTPClient client = new FTPClient();
try {
client.connect(host);
boolean login = client.login(uname, password);
client.getReplyCode(); //230
if (login == true) {
log.debug("Connection established...");
String pwd = client.printWorkingDirectory();
File remotefile = new File(pwd);
boolean rmtfile = remotefile.canWrite();
boolean rmtdir = remotefile.isDirectory();
if(!(remotefile.isDirectory() && remotefile.canWrite())) {
mBuffer.append(MathLogger.raiseError(MathString, "Math is not Writable"));
}
boolean logout = client.logout();
if (logout) {
log.debug("Connection close...");
}
} else {
mBuffer.append(MathLogger.raiseError(MathString, "Connection failed."));
}
} catch (IOException e) {
mBuffer.append(MathLogger.raiseError(MathString, e));
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return mBuffer;
}
mlistFile (or possibly mlistDir) is probably the API you are looking for to call on the remote directory. That returns an FTPFile object that has the permission info. Of course these will only work if the FTP server supports RFC 3659 extensions.
So something like:
FTPFile remoteDir = client.mlistFile(client.printWorkingDirectory());
if (remoteDir.hasPermission(FTPFile.USER_ACCESS,FTPFile.WRITE_PERMISSION)) {
...
}
Related
I have uploaded a file on server 'www.server.com'. Now I wish to know the path of the file on the same server through java code. Is there any specific method or process present? I am new to this.
public class Test {
public static void main(String[] args) {
test test = new test();
String server ="www.server.com";
int port = 21;
String username = "abc";
String password = "abc`enter code here`";
FTPClient ftpclient = new FTPClient();
try {
ftpclient.connect(server, port);
ftpclient.login(username, password);
ftpclient.enterLocalPassiveMode();
ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
File firstLocalFile = new File("D:\\ADF\\Tax Files\\TERData.zip");
String firstRemoteFile = "TERData.zip";
InputStream inputstream = new FileInputStream(firstLocalFile);
System.out.println("Start Uploading the First File");
System.out.println(" File Path ":+firstLocalFile.getAbsolutePath());
boolean done = ftpclient.storeFile(firstRemoteFile, inputstream);
if(done){
System.out.println(" File successfully uploaded ");
}
} catch (IOException e) {
// TODO: Add catch code
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FTPFile[] files1 = ftpClient.listFiles("/test");//"/test/test.txt";
String remoteFile1 =files1[0].getName();
File downloadFile1 = new File("D:/Downloads/test.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.");
}
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 save image in FTP server. But it giving error like java.io.IOException: FTP error: 553 Could not create file.
I call the method
upload("xxx.xx.2.36","ftpuser","xxxxxpos",imageFile,"ftp://ftpuser#xxx.xx.2.36/Item/");
public static void check(FTPClient ftp, String cmd, boolean succeeded) throws IOException {
if (!succeeded) {
throw new IOException("FTP error: " + ftp.getReplyString());
}
}
/**
*
* #return
*/
private static String today() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
public static void upload(String server, String username, String Password,
File imageFile, String destDir) {
FTPClient ftp = new FTPClient();
try {
ftp.connect(server);
check(ftp, "login", ftp.login(username, Password));
System.out.println("Connected to " + server + ".");
InputStream input = new FileInputStream(imageFile);
try {
String destination = destDir;
if (destination.endsWith("/")) {
destination += today()+"-"+imageFile.getName();
System.out.println("direc" +destination);
}
check(ftp, "store", ftp.storeFile(destination, input));
System.out.println("Stored " + imageFile + " to " + destination + ".");
} finally {
input.close();
}
check(ftp, "logout", ftp.logout());
}catch(Exception e){
e.printStackTrace();
}
finally {
try {
ftp.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
After ftp.storeFile(destination, input) it giving error
Please help to solve this.
I'm trying to upload image to my server but when I'm trying to open this image - it's not possible to open, apparently because it's corrupted. Can someone help me and tell me why? thanks!
I'm using the Apache Commons Net jar.
String hostName = "host";
String username = "username";
String password = "pass";
String location = "filePath.png";
FTPClient ftp = null;
InputStream in = null;
try {
ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.changeWorkingDirectory("/pictures");
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if(FTPReply.isPositiveCompletion(reply))
{
System.out.println("Connected Success");
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
File f1 = new File(location);
in = new FileInputStream(f1);
ftp.storeFile("fileName.png",in);
System.out.println("SUCCESS");
in.close();
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
My antivirus was blocking it..
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!