I tried to set the lastmodifeddate of local folder file as the lastmodifieddate of FTP file.
But, in the return value it returns false and date is also not set properly.
Here is the function,
public static void getModifiedDateAndTimeFromFTPFile(String FTPHost, String FTPUserName, String FTPPassword, String FTPRemoteDirectory, String localFilePath, String fileName) {
try{
//get Local File
File fileLocal = new File(localFilePath + fileName);
//Connect to FTP and get the lastmodified time of File.
FTPClient client = new FTPClient();
client.connect(FTPHost);
client.login(FTPUserName, FTPPassword);
client.changeWorkingDirectory(FTPRemoteDirectory);
FTPFile ftpFile = client.listFiles(fileName)[0];
//Get last_modified date of FTP file.
Date ftpFileDate = ftpFile.getTimestamp().getTime();
//Now set date to the Local File.
boolean boolSetTime = fileLocal.setLastModified(ftpFileDate.getTime());
System.out.println(" Was last modified time set successfully ? : " + boolSetTime);
} catch (Exception ex) {
System.out.println("Error : " + ex.toString());
}
}
Can anybody help me by pointing out my mistake?
Thanks
Most probably localFilePath + fileName do not form the intended filename. This won't give you a exception when constructing a File object, but setLastModified(...) would always return false on a non-existing file.
May be it's just a missing path separator?
Related
Before downloading a file needs check whether the file(file name starts) exist or not:
I had a ftp location, it will generate a file in response to hitting a service(API). I need to check whether file exits or not in ftp location using a starting characters of file name because it will append some data at end of file name.
Can any one help on this using java code with commons.net package
Use FTPFileFilter
try {
String filePattern = "prefix";
FTPClient objFTPClient = new FTPClient();
//objFTPClient - set username, password, host, etc...
FTPFileFilter ftpFileFilter = new FTPFileFilter() {
#Override
public boolean accept(FTPFile ftpFile) {
return ftpFile.getName().toLowerCase().startsWith(filePattern.toLowerCase());
}
};
/* List of file that starts with your given prefix */
FTPFile[] ftpFiles = objFTPClient.listFiles(remoteDirectory, ftpFileFilter);
}catch(Exception ex){
ex.printStackTrace();
}finally{
//close connection, etc....
}
I would like to ask if there is a way how to check if file already exists in the folder using only Apache Commons.
I have method which uploads into the SFTP folder but it overwrites current files anytime the method is running. The method is set to run every 5 minutes. I need a code which will create and if statement which checks if the file is not at the SFTP location already and then, if not executes my copy method, if there is a file, then skips it.
My copy method looks like this
private void copyFileSFTP(File model, String hour) throws IOException {
StandardFileSystemManager manager = new StandardFileSystemManager();
String dest = String.format("%s/%s/model/%s", destinationPath, hour,
model.getName());
remoteDirectory = String.format("%s/%s/model/", destinationPath, hour);
try {
if (!model.exists())
LOG.error("Error. Local file not found");
// Initializes the file manager
manager.init();
// Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts,
false);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
// Create the SFTP URI using the host name, userid, password, remote
// path and file name
String sftpUri = "sftp://" + userId + ":" + password + "#"
+ serverAddress + "/" + remoteDirectory + model.getName();
**HERE I NEED THE CHECK IF THE MODEL EXISTS ALREADY ON SFTP**
// Create local file object
FileObject localFile = manager.resolveFile(model.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
// Copy local file to sftp server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
LOG.info("File upload successful");
LOG.info("New file has been created.");
LOG.info(dest);
} catch (Exception ex) {
LOG.error(ex);
handleBadPath(model, hour);
} finally {
manager.close();
}
}
Thank you for help.
Use FileObject.exists() method.
See https://commons.apache.org/proper/commons-vfs/commons-vfs2/apidocs/org/apache/commons/vfs2/FileObject.html#exists--
I am using org.apache.commons.net.ftp.FTPClient for retrieving files from a ftp server. It is crucial that I preserve the last modified timestamp on the file when its saved on my machine. Do anyone have a suggestion for how to solve this?
This is how I solved it:
public boolean retrieveFile(String path, String filename, long lastModified) throws IOException {
File localFile = new File(path + "/" + filename);
OutputStream outputStream = new FileOutputStream(localFile);
boolean success = client.retrieveFile(filename, outputStream);
outputStream.close();
localFile.setLastModified(lastModified);
return success;
}
I wish the Apache-team would implement this feature.
This is how you can use it:
List<FTPFile> ftpFiles = Arrays.asList(client.listFiles());
for(FTPFile file : ftpFiles) {
retrieveFile("/tmp", file.getName(), file.getTimestamp().getTime());
}
You can modify the timestamp after downloading the file.
The timestamp can be retrieved through the LIST command, or the (non standard) MDTM command.
You can see here how to do modify the time stamp: that: http://www.mkyong.com/java/how-to-change-the-file-last-modified-date-in-java/
When download list of files, like all files returned by by FTPClient.mlistDir or FTPClient.listFiles, use the timestamp returned with the listing to update timestemp of local downloaded files:
String remotePath = "/remote/path";
String localPath = "C:\\local\\path";
FTPFile[] remoteFiles = ftpClient.mlistDir(remotePath);
for (FTPFile remoteFile : remoteFiles) {
File localFile = new File(localPath + "\\" + remoteFile.getName());
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
if (ftpClient.retrieveFile(remotePath + "/" + remoteFile.getName(), outputStream))
{
System.out.println("File " + remoteFile.getName() + " downloaded successfully.");
}
outputStream.close();
localFile.setLastModified(remoteFile.getTimestamp().getTimeInMillis());
}
When downloading a single specific file only, use FTPClient.mdtmFile to retrieve the remote file timestamp and update timestamp of the downloaded local file accordingly:
File localFile = new File("C:\\local\\path\\file.zip");
FTPFile remoteFile = ftpClient.mdtmFile("/remote/path/file.zip");
if (remoteFile != null)
{
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
if (ftpClient.retrieveFile(remoteFile.getName(), outputStream))
{
System.out.println("File downloaded successfully.");
}
outputStream.close();
localFile.setLastModified(remoteFile.getTimestamp().getTimeInMillis());
}
I'm writing an app in which I'm saving photos in internal storage. I'm using solution from this blog
I know names of two files before, so I can have in a code, but in my app there will be also a gallery. So my question is: how to save files without knowing their name(file name is generated using date and time)? Content provider's oncreate starts during initialisation so how to pass new files names to content provider?
Thanks in advance.
In the content provider class remove in onCreate the file creation completely.
public static String lastPictureSaved = "";
Change the function openFile. There the filename will be made accordig to date time and the file created.
Date date = new Date();
date.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
String datetimestr = formatter.format(date);
lastPictureSaved = getContext().getFilesDir() + "/" + datetimestr + ".jpg";
File f = new File(lastPictureSaved);
try
{
f.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
Log.d(TAG, e.getMessage());
}
in the Host activity change
File out = new File(getFilesDir(), "newImage.jpg");
to
File out = new File(MyFileContentProvider.lastPictureSaved);
I have a java program that call my Perl script to upload a file. It has a file parameter to the Perl script that contain the location of file to upload.
public static void legacyPerlInspectionUpload(String creator, String artifactId, java.io.File uploadedFile, String description ) {
PostMethod mPost = new PostMethod(getProperty(Constants.PERL_FILE_URL) + "inspectionUpload.pl");
try {
String upsSessionId = getUpsSessionCookie();
//When passing multiple cookies as a String, seperate each cookie with a semi-colon and space
String cookies = "UPS_SESSION=" + upsSessionId;
log.debug(getCurrentUser() + " Inspection File Upload Cookies " + cookies);
Part[] parts = {
new StringPart("creator", creator),
new StringPart("artifactId", artifactId),
new StringPart("fileName", uploadedFile.getName()),
new StringPart("description", description),
new FilePart("fileContent", uploadedFile) };
mPost.setRequestEntity(new MultipartRequestEntity(parts, mPost.getParams()));
mPost.setRequestHeader("Cookie",cookies);
HttpClient httpClient = new HttpClient();
int status = httpClient.executeMethod(mPost);
if (status == HttpStatus.SC_OK) {
String tmpRetVal = mPost.getResponseBodyAsString();
log.info(getCurrentUser() + ":Inspection Upload complete, response=" + tmpRetVal);
} else {
log.info(getCurrentUser() + ":Inspection Upload failed, response=" + HttpStatus.getStatusText(status));
}
} catch (Exception ex) {
log.error(getCurrentUser() + ": Error in Inspection upload reason:" + ex.getMessage());
ex.printStackTrace();
} finally {
mPost.releaseConnection();
}
}
In this part of my Perl script, it get the information about the file, read from it and write the content to a blink file in my server.
#
# Time to upload the file onto the server in an appropropriate path.
#
$fileHandle=$obj->param('fileContent');
writeLog("fileHandle:$fileHandle");
open(OUTFILE,">$AttachFile");
while ($bytesread=read($fileHandle,$buffer,1024)) {
print OUTFILE $buffer;
}
close(OUTFILE);
writeLog("Download file, checking stats.");
#
# Find out if the file was correctly uploaded. If it was not the file size will be 0.
#
($size) = (stat($AttachFile))[7];
Right now the problem is this only work for file with no space in its name, otherwise $size is 0. I was reading online and it seems both Java file and Perl filehandle work with space, so what am I doing wrong?
Your poor variable naming has tripped you up:
open(OUTFILE,">$AttachFile");
^^^^^^^---this is your filehandle
while ($bytesread=read($fileHandle,$buffer,1024)) {
^^^^^^^^^^^--- this is just a string
You're trying to read from something that's NOT a filehandle, it's just a variable whose name happens to be "filehandle". You never opened up the specified file for reading. e.g. you're missing
open(INFILE, "<$fileHandle");
read(INFILE, $buffer, 1024);