Java File exists Case sensitive .jpg and .JPG - java

I use this function to detect if my file exists or not. While I have some image stored as .jpg, .JPG, .png, and .PNG. But it always return .jpg or .png as true even if the real file has extension .JPG or .PNG.
After I render it to my webpage it throws an error "Failed to load resource: the server responded with a status of 404 (Not Found)".
public static String getPhotoFileExtension(int empKey){
try{
String[] types = {".jpg",".JPG",".png", ".PNG"};
for(String t : types)
{
String path = "/"+Common.PHOTO_PATH + empKey + t;
File f = new File(Sessions.getCurrent().getWebApp()
.getRealPath(path));
if(f.isFile())
return t;
}
}catch (Exception e) {
e.printStackTrace();
}
return "";
}

So you want to get the real case sensitive names of files stored in your filesystem. Lets imaging we have the following paths:
on Linux: using ext4 (which is case sensitive) /testFolder/test.PnG
on Windows using NTFS (which is not case sensitive) c:\testFolder\test.PnG
Now lets create some Java File Objects to each Image File.
// on Linux
File f1 = new File("/testFolder/test.png");
File f2 = new File("/testFolder/test.PNG");
File f3 = new File("/testFolder/test.PnG");
f1.exists(); // false
f2.exists(); // false
f3.exists(); // true
// on Windows
File f1 = new File("c:\\testFolder\\test.png");
File f2 = new File("c:\\testFolder\\test.PNG");
File f3 = new File("c:\\testFolder\\test.PnG");
f1.exists(); // true
f2.exists(); // true
f3.exists(); // true
Your problem is that all calls of File like File.exists are redirected to the java.io.FileSystem class that represents real Operating System calls of your File System by the JVM. So you cannot distinguish on Windows Machines between test.PNG and test.png. Neither do Windows itself.
But even on Windows each File has a defined name in the File System that could be for example: test.PnG. You will see this in your Windows Explorer or in Command Line if you type dir c:\testFolder.
So what you can do in Java is use the File.list method on the parent directory that results in the Operating System list call for all files in this directory with their real names.
File dir = new File("c://testFolder//");
for(String fileName : dir.list())
System.out.println(fileName);
// OUTPUT: test.PnG
or if you prefer File Objects
File dir = new File("c://testFolder//");
for(File file : dir.listFiles())
System.out.println(file.getName());
// OUTPUT: test.PnG
You can use this to write your own exists Method that is case sensitive on all operating systems
public boolean exists(File dir, String filename){
String[] files = dir.list();
for(String file : files)
if(file.equals(filename))
return true;
return false;
}
Use it like this:
File dir = new File("c:\\testFolder\\");
exists(dir, "test.png"); // false
exists(dir, "test.PNG"); // false
exists(dir, "test.PnG"); // true
EDIT: I have to admit that I was wrong. There is a way to get the real name of a File. I always overlooked the method File.getCanonicalPath.
Again our example: We have that File c:\testFolder\test.PnG.
File f = new File("c://testFolder//test.png");
System.out.println(f.getCanonicalPath());
// OUTPUT: C:\testFolder\test.PnG
With that knowledge you can write a simple test method for the case sensitive extension without iterating all files.
public boolean checkExtensionCaseSensitive(File _file, String _extension) throws IOException{
String canonicalPath = _file.getCanonicalPath();
String extension = "";
int i = canonicalPath.lastIndexOf('.');
if (i > 0) {
extension = canonicalPath.substring(i+1);
if(extension.equals(_extension))
return true;
}
return false;
}
Use it like this:
File f = new File("c://testFolder//test.png");
checkExtensionCaseSensitive(f, "png"); // false
checkExtensionCaseSensitive(f, "PNG"); // false
checkExtensionCaseSensitive(f, "PnG"); // true

If you are looking for a function that in any platform can determine existence of a file and is case-sensitive; this should do it :
public static boolean fileExistsCaseSensitive(String path) {
try {
File file = new File(path);
return file.exists() && file.getCanonicalFile().getName().equals(file.getName());
} catch (IOException e) {
return false;
}
}

I started messing around a little with this because I haven't used Apache's IOFileFilter before and thought that I would add this solution as a chance to play with it a little.
Here is the code:
import java.io.File;
import java.util.Collection;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
public class CaseInsensitiveFileFinder {
/**
* Attempts to find a file with the given <code>fileName</code> (irrespective of case) in the given
* <code>absoluteDirPath</code>. Note that while this method is able to find <code>fileName</code> ignoring case, it
* may not be able to do so if <code>absoluteDirPath</code> is in an incorrect case - that behavior is OS dependent.
*
* #param absoluteDirPath the absolute path of the parent directory of <code>fileName</code> (e.g. "/Users/me/foo")
* #param fileName the name of the file including extension that may or may not be the correct case
* (e.g. myfile.txt)
* #return an optional reference to the file if found, {#link Optional#empty()} will be returned if the file is not
* found
*/
public Optional<File> findFileIgnoreCase(String absoluteDirPath, final String fileName) {
File directory = new File(absoluteDirPath);
if (!directory.isDirectory()) {
throw new IllegalArgumentException("Directory '" + absoluteDirPath + "' isn't a directory.");
}
IOFileFilter caseInsensitiveFileNameFilter = new IOFileFilter() {
#Override
public boolean accept(File dir, String name) {
boolean isSameFile = fileName.equalsIgnoreCase(name);
return isSameFile;
}
#Override
public boolean accept(File file) {
String name = file.getName();
boolean isSameFile = fileName.equalsIgnoreCase(name);
return isSameFile;
}
};
Collection<File> foundFiles = FileUtils.listFiles(directory, caseInsensitiveFileNameFilter, null);
if (foundFiles == null || foundFiles.isEmpty()) {
return Optional.empty();
}
if (foundFiles.size() > 1) {
throw new IllegalStateException(
"More requirements needed to determine what to do with more than one file. Pick the closest match maybe?");
}
// else exactly one file
File foundFile = foundFiles.iterator().next();
return Optional.of(foundFile);
}
}
And here are some test cases:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.io.Files;
/**
* Non-quite-unit tests for {#link CaseInsensitiveFileFinder} class.
*/
public class CaseInsensitiveFileFinderTest {
private static String APPENDABLE_NEW_TMP_DIR_PATH;
/**
* Create the files with different cases.
* #throws IOException
*/
#BeforeClass
public static void setup() throws IOException {
File newTmpDir = Files.createTempDir();
String newTmpDirPath = newTmpDir.getCanonicalPath();
final String appendableNewTmpDirPath;
String fileSeparator = System.getProperty("file.separator");
if (!newTmpDirPath.endsWith(fileSeparator)) {
appendableNewTmpDirPath = newTmpDirPath + fileSeparator;
}
else {
appendableNewTmpDirPath = newTmpDirPath;
}
CaseInsensitiveFileFinderTest.APPENDABLE_NEW_TMP_DIR_PATH = appendableNewTmpDirPath;
File foofileDotPng = new File(appendableNewTmpDirPath + "FOOFILE.PNG");
Files.touch(foofileDotPng);
assertTrue(foofileDotPng.isFile());
File barfileDotJpg = new File(appendableNewTmpDirPath + "BARFILE.JPG");
Files.touch(barfileDotJpg);
assertTrue(barfileDotJpg.isFile());
}
#AfterClass
public static void teardown() throws IOException {
File newTmpDir = new File(CaseInsensitiveFileFinderTest.APPENDABLE_NEW_TMP_DIR_PATH);
assertTrue(newTmpDir.isDirectory());
// delete even though directory isn't empty
FileUtils.deleteDirectory(newTmpDir);
}
#Test
public void findFooFilePngUsingLowercase() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "foofile.png");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "FOOFILE.PNG", foundFile.getCanonicalPath());
}
#Test
public void findBarFileJpgUsingLowercase() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "barfile.jpg");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "BARFILE.JPG", foundFile.getCanonicalPath());
}
#Test
public void findFileThatDoesNotExist() {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "dne.txt");
assertFalse(optFoundFile.isPresent());
}
#Test
public void findFooFileUsingDirWithNoTrailingFileSeparator() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
String newDirPathWithNoTrailingFileSep = StringUtils.chop(APPENDABLE_NEW_TMP_DIR_PATH);
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(newDirPathWithNoTrailingFileSep, "FOOFILE.PNG");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "FOOFILE.PNG", foundFile.getCanonicalPath());
}
}
Hope that helps.

Instead of returning t (the file extension) return the file Object. That way your certain that you have the correct file. If you don't want to return the file object return the file name with the extension.
public static File getPhotoFileExtension(int empKey){
try{
String[] types = {".jpg",".JPG",".png", ".PNG"};
for(String t : types)
{
String path = "/"+Common.PHOTO_PATH + empKey + t;
File f = new File(Sessions.getCurrent().getWebApp()
.getRealPath(path));
if(f.isFile())
return f;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}

With that NiMa Thr said, you can do what you are looking for with this code :
On Windows, if the file exists, with any case, it will return true. If the file doesn't exists, the canonical name will be the same, so it will return false.
On Linux, if the file exists with a different case, the canonical name will return this different name, and the method will return true.
public static boolean fileExistsCaseInsensitive(String path) {
try {
File file = new File(path);
return file.exists() || !file.getCanonicalFile().getName().equals(file.getName());
} catch (IOException e) {
return false;
}
}

Related

Java - Can't find and load a CSV file

For some reason, although I have already downloaded the CSV files, my program is unable to read them. My code is below, and it checks if the CSV file exists. If it does not, it goes to the URL and downloads and reads the code. However, it always re-downloads the code although it is in the path folder.
private void loadData(String path, String url) throws IOException{
File f = new File(path);
System.out.println("looking for path " + path);
if(f.exists()) {
readSavedFile(path); //method to load data
}
else{
System.out.println("Need to download from internet");
downloadAndRead(url, path);
}
}
This code outputs
looking for path C:\Users\n_000\workspace\Program\GOOG.csv
Need to download from internet.
looking for path C:\Users\n_000\workspace\Program\CHK.csv
Need to download from internet.
The code that I'm using to create the path is this:
String save = "filename"; //in program use this is the name of the stock eg GOOG or CHK
Path currentRelativePath = Paths.get("");
String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\";
path = savedFolder+save+".csv";
Its working fine,i didn't see any issues,i am posting my tested code,hope it may be useful.
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String ar[])
{
Test test=new Test();
}
public Test()
{
String save = "GOOG"; //in program use this is the name of the stock eg GOOG or CHK
Path currentRelativePath = Paths.get("");
String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\";
String path = savedFolder+save+".csv";
String url=null;
try
{
loadData(path,url);
} catch (IOException e)
{
e.printStackTrace();
}
}
private void loadData(String path, String url) throws IOException
{
File f = new File(path);
System.out.println("looking for path " + path);
if(f.exists()) {
readSavedFile(path); //method to load data
}
else{
System.out.println("Need to download from internet");
downloadAndRead(url, path);
}
}
public void readSavedFile(String path)
{
System.out.println("Reading file");
}
public void downloadAndRead(String url,String path)
{
System.out.println("Downloding file");
}
}

Google Drive uploading a file, and reading a file

.Net guy working on a java app
I am uploading using the following example as my starting point ( I have this working). This shows using FileContent needing a java.io.File which does not contain the actual file only a pointer to the actual file.
We are uploading from a web site and attempting to insert into the drive, I would prefer to do this using a memory Stream like the .Net example. I cannot see that in looking at the FileContent class. So my questing is: Is there a way to insert a file in Google drive that is in memory and not first on the hard drive?
private static File insertFile(Drive service, String title, String description,
String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
// Set the parent folder.
if (parentId != null && parentId.length() > 0) {
body.setParents(
Arrays.asList(new ParentReference().setId(parentId)));
}
// File's content.
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
// Uncomment the following line to print the File ID.
// System.out.println("File ID: " + file.getId());
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
Override the AbstractInputStream build your own FileContent
package com;
import java.io.IOException;
import java.io.InputStream;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.util.Preconditions;
public class FileContent extends AbstractInputStreamContent {
private InputStream inputStream = null;
private long inputLength = 0;
public FileContent(String type, InputStream pInputStream) throws IOException {
super(type);
this.inputStream = Preconditions.checkNotNull(pInputStream);
this.inputLength = this.inputStream.available();
}
public long getLength() throws IOException {
return this.inputLength;
}
public boolean retrySupported() {
return false;
}
#Override
public InputStream getInputStream() throws IOException {
return this.inputStream;
}
}

How can I get duplicated values from ArrayList?

There is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class CompareFile {
CompareFile() {}
boolean check = false;
int count = 0;
/*
* this method return a File type variable
* variable path - this parameter takes a path in specified root
* also it's a private method and he should be called with help by class object
*/
public File find(File path) throws FileNotFoundException {
PrintWriter writer = new PrintWriter("D:/Photos/name.txt");
ArrayList<String> buffer = new ArrayList<String>();
/*
* let's create array of files
* where must be all found files
* We use File[], and named 'files'
* variable files takes on list of found files
* with help by listFiles method, that
* return list of files and directories
*/
File[] files = path.listFiles();
//System.out.println(files.toString());
try {
/*
* we'll ought use the for each loop
* in this loop we'll create File type variable 'file'
* then we'll do iterating for each expression from variable files
*/
for (File file : files) {
//print all found files and directories
//if file or directory exists
if (file.isDirectory()) {
//recursively return file and directory
find(file);
}
else {
buffer.add(file.getName());
System.out.println(file);
}
}
}
catch (Exception e) {
System.out.print("Error");
}
finally{
if ( writer != null )
writer.close();
}
/*
Iterator<String> i = buffer.iterator();
while(i.hasNext()) {
System.out.println(i.next());
}*/
return path;
}
public static void main(String[] args) throws FileNotFoundException {
File mainFile = new File("D:/Photos/");
CompareFile main = new CompareFile();
main.find(mainFile);
}
}
If I use sort, after sorting, the result bad, because first row from dir "Photos",
and second row from directory in directory "Photos/sub" Let's look at
the screen: I think you understand)
http://s10.postimg.org/7hcw83z9x/image.png
You'll need to keep track of where you are in the tree, change the find method to take a path:
public File find(File path, string path="") throws FileNotFoundException
When you call the find method recursively:
find(file, path + file.getName() + "/")
Then when you add to the list, use
buffer.add(path + file.getName());

Failed to move file to another directory using renameTo

import java.io.File;
import org.apache.commons.io.FilenameUtils;
public class Tester {
public static void main(String[] args) {
String rootPath = "F:\\Java\\Java_Project";
File fRoot = new File(rootPath);
File[] fsSub = fRoot.listFiles();
for (File file : fsSub) {
if(file.isDirectory()) continue;
String fileNewPath = FilenameUtils.removeExtension(file.getPath()) + "\\" + file.getName();
File fNew = new File(fileNewPath);
try {
file.renameTo(fNew);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am trying to move the file to another directory,for instance,if the File path is
"C:\out.txt"
than I want to move to
"C:\out\out.txt"
If i try to print the original File and the new original information, the work well,But they just can not move successful.
I suggest to try Java 7 NIO2
Files.move(Path source, Path target, CopyOption... options)

File/Directory synchronization in Java using JSch?

Is it possible to do file/directory sync in Java using JSch ? I need to sync directory from a remote linux machine to my local windows machine. Is this possible ?
-Tivakar
The easiest way to download files from SCP server is using Commons VFS along with JSch:
import java.io.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.vfs2.*;
public class CopyRemoteFile {
public static void copyRemoteFiles(String host, String user, String remotePath, String localPath) throws IOException {
FileSystemOptions fsOptions = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
SftpFileSystemConfigBuilder.getInstance().setIdentities(fsOptions,
new File[] { new File(FileUtils.getUserDirectoryPath() + "/.ssh/id_dsa") });
DefaultFileSystemManager fsManager = (DefaultFileSystemManager) VFS.getManager();
String uri = "sftp://" + user + "#" + host + "/" + remotePath;
FileObject fo = fsManager.resolveFile(uri, fsOptions);
FileObject[] files = fo.getChildren();
for (FileObject file : files) {
// We will be dealing with the files here only
if (file.getType() == FileType.FILE) {
FileUtils.copyInputStreamToFile(file.getContent().getInputStream(),
new File(localPath + "/" + file.getName().getBaseName()));
}
file.close();
}
fo.close();
fsManager.close();
}
}
It's just an example I got in my Wiki, so nothing fancy. But do keep in mind that if you'll close fsManager, you will not be able to open it again in the same VM. I got this issue while testing this solution...
Although the example above does not import any JSch classes, you need to put it in the classpath anyway.
The above example is using private key to authenticate with the remote host. You can easily change that by providing password and modifying the uri to include that.
If you need to sync files, you can compare dates of the files on the local file system (or DB, or any other source of the information) and the remote files:
import java.io.*;
import org.apache.commons.io.*;
import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.impl.*;
import org.apache.commons.vfs2.provider.sftp.*;
public class CopyRemoteFile {
public static void copyRemoteFiles(final String host, final String user, final String remotePath, final String localPath)
throws IOException {
FileSystemOptions fsOptions = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
SftpFileSystemConfigBuilder.getInstance().setIdentities(fsOptions,
new File[] { new File(FileUtils.getUserDirectoryPath() + "/.ssh/id_dsa") });
DefaultFileSystemManager fsManager = (DefaultFileSystemManager) VFS.getManager();
String uri = "sftp://" + user + "#" + host + "/" + remotePath;
FileObject fo = fsManager.resolveFile(uri, fsOptions);
FileObject[] files = fo.getChildren();
for (FileObject file : files) {
// We will be dealing with the files here only
File newFile = new File(localPath + "/" + file.getName().getBaseName());
if (file.getType() == FileType.FILE && newFile.lastModified() != file.getContent().getLastModifiedTime()) {
FileUtils.copyInputStreamToFile(file.getContent().getInputStream(), newFile);
newFile.setLastModified(file.getContent().getLastModifiedTime());
}
file.close();
}
fo.close();
fsManager.close();
}
}
Look at: http://the-project.net16.net/Projekte/projekte/Projekte/Programmieren/sftp-synchronisierung.html
There is a whole Programm uploadet.
Here is the sync Part:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Vector;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.SftpException;
/*
* This is the heart of the whole Program. I hope, the descriptions are precise enought.
*/
public class Sync{
public String ServerPath;
public File LocalFolder;
public sFTPclient client;
public ArrayList<String> serverContentList;
public ArrayList<String> pathList;
public Sync(File local, String to, sFTPclient client){
this.LocalFolder = local;
this.ServerPath = to;
this.client = client;
}
/*
* Executed once. Sets the Server Directory if it exists.
* If the local folder doesn't exist on the Server, it creates it.
*/
public void setServerDirectory() throws SftpException{
try{
client.sftpChannel.cd(ServerPath);
}catch(Exception e){
GUI.addToConsole(ServerPath + " don't exist on your server!");
}
String serverFolder = ServerPath.substring(ServerPath.lastIndexOf('/')+1, ServerPath.length());
if(!LocalFolder.getName().equals(serverFolder)){
try{
client.sftpChannel.mkdir(LocalFolder.getName());
client.sftpChannel.cd(LocalFolder.getName());
} catch (Exception e){
client.sftpChannel.cd(LocalFolder.getName());
}
this.ServerPath = ServerPath + "/" + LocalFolder.getName();
GUI.setNewServerFolder(ServerPath);
}
serverContentList = new ArrayList<String>();
pathList = new ArrayList<String>();
}
//The contentlist contains all Filenames, that should be synchronized
public void setToContentList(String ServerFolder) throws SftpException{
#SuppressWarnings("unchecked")
Vector<LsEntry> fileList = client.sftpChannel.ls(ServerFolder);
int size = fileList.size();
for(int i = 0; i < size; i++){
if(!fileList.get(i).getFilename().startsWith(".")){
serverContentList.add(fileList.get(i).getFilename());
pathList.add(ServerFolder);
}
}
}
/*
* Deletes the synchronized elements from the Lists
*/
public void deleteFromLists(String name){
int position = serverContentList.lastIndexOf(name);
if(position >= 0){
serverContentList.remove(position);
pathList.remove(position);
}
}
/*
* Main function for synchronizing. Works recursive for local folders.
*/
#SuppressWarnings("unchecked")
public void synchronize(File localFolder, String ServerDir) throws SftpException, FileNotFoundException{
if(client.sftpChannel.pwd() != ServerDir){
client.sftpChannel.cd(ServerDir);
}
setToContentList(ServerDir);
File[] localList = localFolder.listFiles();
Vector<LsEntry> ServerList = client.sftpChannel.ls(ServerDir);
ServerList.remove(0); ServerList.remove(0);
/*
* Upload missing Files/Folders
*/
int size = localList.length;
for(int i = 0; i < size; i++){
if(localList[i].isDirectory()){
if(checkFolder(localList[i], ServerDir)){
synchronize(localList[i], ServerDir + "/" + localList[i].getName());
deleteFromLists("SubFolder");
}else {
newFileMaster(true, localList[i], ServerDir);
}
} else {
checkFile(localList[i], ServerDir);
}
deleteFromLists(localList[i].getName());
}
}
/*
* Deletes all files on the server, which are not in the local Folder. Deletes also all missing folders
*/
public void deleteRest() throws SftpException, FileNotFoundException{
int size = serverContentList.size();
for(int i = 0; i < size; i++){
client.sftpChannel.cd(pathList.get(i));
newFileMaster(false, null, serverContentList.get(i));
}
}
/*
* Copy or delete Files/Folders
*/
public void newFileMaster(boolean copyOrNot, File sourcePath, String destPath) throws FileNotFoundException, SftpException{
FileMaster copy = new FileMaster(copyOrNot, sourcePath, destPath, client.sftpChannel);
copy.runMaster();
}
/*
*Useful to find errors - Prints out the content-List every time you call the method.
*If you have Problems, call it before and after every changes of the serverContentList!
*/
/*public void printServerContent(){
System.out.println("SERVER-Content: " + "\n");
for(int i = 0; i < serverContentList.size(); i++){
System.out.println(serverContentList.get(i) + " in " + pathList.get(i));
}
}*/
/*
* Looks ond the server, if the file is there. If not, or the local file has changed, it copies the file on the server.
*/
public void checkFile(File file, String path) throws SftpException, FileNotFoundException{
client.sftpChannel.cd(path);
if(!serverContentList.contains(file.getName())){
newFileMaster(true, file, ServerPath);
} else {
Long localTimeStamp = file.lastModified();
Long timeStamp = client.sftpChannel.stat(file.getName()).getATime()*1000L;
if(localTimeStamp > timeStamp){
newFileMaster(false, null, path + "/" + file.getName());
newFileMaster(true, file, path);
}
}
deleteFromLists(file.getName());
}
/*
* The same as the checkFile function. But it returns a boolean. (Easier to handle in the synchronized funtion)
* Don't check, if the folder has changed (I think this can't be the case)
*/
public boolean checkFolder(File folder, String path) throws SftpException{
client.sftpChannel.cd(path);
if(serverContentList.contains(folder.getName())){
return true;
}else { return false; }
}
}

Categories

Resources