Show issue while deleting directory [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Delete a folder on SD card
In my app i saved all my data using internal storage i.e file. So at the first instance by using the ContextWrapper cw = new ContextWrapper(getApplicationContext()); class i get the directory path as m_AllPageDirectoryPath = cw.getDir("AllPageFolder", Context.MODE_PRIVATE); Inside this directory path i saved some file File as Page01, page02, Page03 and so on.
Again inside Page01 i saved some file like image01, image02...using the same concept m_PageDirectoryPath = cw.getDir("Page01", Context.MODE_PRIVATE); Now on delete of m_AllPageDirectoryPath i want to delete all the file associate with it. I tried using this code but it doesn't work.
File file = new File(m_AllPageDirectoryPath.getPath());
file.delete();

Your code only works if your directory is empty.
If your directory includes Files and Sub Directories, then you have to delete all files recursively..
Try this code,
// Deletes all files and subdirectories under dir.
// Returns true if all deletions were successful.
// If a deletion fails, the method stops attempting to delete and returns false.
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
(Actually you have to search on internet before asking like this questions)

Related

Automation : Move files from source folder to destination folder one by one and delete the file from source folder [duplicate]

This question already has answers here:
Update : Move files from one folder to another based on file extension
(3 answers)
Closed 4 years ago.
Scenario :
I have 2 files in the DOWNLOAD folder.
1. A.csv
2. B.csv
A.csv gets downloaded first and then B.csv gets downloaded.
I want to move A.csv to Folder1 and as soon as the file is moved, A.csv should get deleted from download folder and then B.csv file should get downloaded and it should be moved to Folder2 and as soon as the file is moved, B.csv should get deleted from download folder.
My Code :
I am getting "The method copyDirectory(File, File, boolean) in the type FileUtils is not applicable for the arguments (File, File, new FileFilter(){})" error in the FileUtils.copyDirectory(source, dest, new FileFilter() line. My code is as follows:
List<WebElement> list= wd.findElements(By.xpath("//table[#class='lcb']/tbody/tr/td/table[#class='ibody']/tbody/tr/td[contains(translate(text(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'csv')]/parent::tr/td[7]/a"));
for (WebElement element:list)
{
element.click();
++count;
if(count==1)
{
try{
File source = new File("C:\\Users\\sh370472\\Downloads");
File dest = new File("E:\\PAS\\");
FileUtils.copyDirectory(source, dest, new FileFilter() {
#Override
public boolean accept(File pathname)
{
boolean source=pathname.getName().toLowerCase().endsWith(".csv");
if (source)
{
pathname.deleteOnExit();
return true;
}
return false;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Thread.sleep(9000);
if(count==2)
{
File source1 = new File("C:\\Users\\sh370472\\Downloads");
File dest1 = new File("E:\\TAS\\");
FileUtils.copyDirectory(source1, dest1, new FileFilter() {
#Override
public boolean accept(File pathname)
{
boolean source1=pathname.getName().toLowerCase().endsWith(".csv");
if (source1)
{
pathname.deleteOnExit();
return true;
}
return false;
}
});
}
}
Can somebody tell me how to rectify this error or suggest any alternative
FileUtils isn't a standard java utility class, but from your error message copyDirectory takes a Boolean as the last parameter, not a filter. You should figure out if there is another method that takes the filter.
Even with that solved, I don't ever see where you download a file. You are copying from source to dest but both of those are directories--neither is an FTP site.
You need to start by downloading a list of files from your FTP site then you can loop over that list and download/copy/delete each one.
You never use your WebElement parameter--is that where your file list is coming from?

Moving files is not working in java [duplicate]

This question already has answers here:
How do I move a file from one location to another in Java?
(11 answers)
Closed 6 years ago.
i'm trying in a loop to move files after they are loaded and processed...when I test moving file part individually it works but when I do it all at once it does not work.
Bellow works fine, but moves directories also but I want only the file to be moved.
public class moveFiles {
public static void main(String[] args) {
String getFilesFrom = "D:\\show\\from";
String destDir = "D:\\show\\to\\";
File srcFile = new File(getFilesFrom);
srcFile.renameTo(new File(destDir, srcFile.getName()));
}
}
The code that I have which is not working the moving part is bellow.
for (File child : file.listFiles()) {
if(extensionFilter.accept(child)) {
fr = new FileReader(child);
cm.copyIn("COPY ct"+addExtraZero+month+" FROM STDIN WITH DELIMITER ',' csv", fr);
} else {
System.out.println("No File is elgible to be loaded");
break;
}
getNumberOfFilesProcessed++;
System.out.println("Loading now " + child.getName());
child.renameTo(new File(moveFilesTo, child.getName()));
}
System.out.println("Number of files Loaded is: " + getNumberOfFilesProcessed);
The above code is:
get files from source directory,
loaded it in database
print files name that it loads
get count of files loaded
which all above works but the last part which is to move files to other directory after loading is not working bellow is the section of files that suppose to move the file the loop.
child.renameTo(new File(moveFilesTo, child.getName()));
scratching my heads for two hours any help will be appreciated.
From description of File.renameTo() (emphasis mine):
The rename operation might not be able to move a file from one
filesystem to another, it might not be atomic, and it might not
succeed if a file with the destination abstract pathname already
exists. The return value should always be checked to make sure that
the rename operation was successful
Add:
if( !child.renameTo(new File(moveFilesTo, child.getName())) )
System.out.println("Could not move file");
Or try using move(Path, Path, CopyOption...) method, as this has more options (using File.toPath()).

What is the right way to check if a file is in a directory?

I am not asking how to check if a file exists or how to check if a file is in a specific directory level. Rather I want to know how to check if an existing file is anywhere underneath a specified directory.
Obviously if a file is a direct child of a directory that is easy to check. But what I want to be able to do is efficiently check if an existing file is in a directory including any possible subdirectory. I'm using this in an Android project where I am keeping fine grain control over my cache and I want a utility method to check if a file I may be manipulating is in my cache folder.
Example:
cache dir
/ \
dir file1
/ \
file2 file3
isCacheFile(file2) should return true
Currently I have a method that does it like so
private static final File cacheDir = AssetManager.getInstance().getCacheDir(); // Not android.content.res.AssetManager
private static final String cacheDirName = cacheDir.getAbsolutePath();
public static boolean isCacheFile(File f) {
if (!f.exists()) return false;
return f.getAbsolutePath().startsWith(cacheDirName);
}
However, I am inclined to believe there is a better way to do this. Does anyone have any suggestions?
If you have a known path (in the form of File f), and you want to know if it is inside a particular folder (in the form of File cacheDir), you could simply traverse the chain of parent folders of your file and see if you meet the one you are looking for.
Like this:
public static boolean isCacheFile(File f) {
while (f.getParentDir()!=null) {
f = f.getParentDir();
if (f.equals(cacheDir)) {
return true;
}
}
return false;
}
boolean isContains(File directory){
File[] contents = directory.listFiles();
if (contents != null) {
for(int i = 0; i < contents.length; i++){
if(contents[i].isDirectory())
isContains(contents[i]);
else if(contents[i].getName().equals(*your_file_name*))
return true;
}
}
return false;
}
You could do it by recursion, by calling if the file exists in each sub-directory.
first check if the file exists in the root directory.
boolean exist = new File(rootDirectory, temp).exists();
then if the file wasn't in the root directory, then list all the files and call the method again in the sub-directoy files recursionally until you find the file or there are no more sub-directories.
public String getPathFromFileName(String dirToStart,Sring fileName){
File f = new File(dirToStart);
File[] list = f.listFiles();
String s="null";
for(int i=0;i<list.length;i++){
if(list[i].isFile()){
//is a file
if(fileName.equals(list[i])){
s=dirToStart+"/"+fileName;
break;
}
}else{
//is a directory search further.
getPathFromFileName(dirToStart+list[i]);
}
}
return s;
}
call this method by passing the parent directory name and the file name to search in subdirectories.
you check the return value if it is not equal to "null", then the files path is returned.

Loading files from java jar file [duplicate]

This question already has answers here:
Get resource from jar
(4 answers)
Closed 9 years ago.
Hi I am stuck with following code. I would like to get files from folder but when I export project to jar file it wont work any idea?
public String getXSDfilenames() {
String filenames= "";
try {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length()-1);
File file = new File(path+"src\\schemaFiles");
String[] files = file.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xsd");
}
});
if (file.exists()) {
for (int i = 0; i < files.length; i++) {
System.out.println(path+"src\\schemaFiles\\"+files[i]);
filenames = filenames + files[i] + newline;
}
} else {
System.out.println("No schema files founded in default folder!");
}
}
catch (Throwable e1) {
System.out.println(e1);
}
return filenames;
}
}
If you change the name of your XXX.jar file to XXX.zip, then open it in whatever Zip file utility you might have available, you can look inside the file and see 1. Whether your files are getting included in the jar at all, and if they are, 2. the actual path in which they are stored. I strongly suspect there's now src folder inside your jar.
Also, if you're NOT expecting the files to be in the jar, then you'll probably need to supply an absolute path to the files.
If they are in the jar, then check out these questions:
load file within a jar,
How to use ClassLoader.getResources() correctly?,
How do I list the files inside a JAR file?

Move all files from folder to other folder with java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Copying files from one directory to another in Java
How can I move all files from one folder to other folder with java?
I'm using this code:
import java.io.File;
public class Vlad {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// File (or directory) to be moved
File file = new File("C:\\Users\\i074924\\Desktop\\Test\\vlad.txt");
// Destination directory
File dir = new File("C:\\Users\\i074924\\Desktop\\Test2");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
System.out.print("not good");
}
}
}
but it is working only for one specific file.
thanks!!!
By using org.apache.commons.io.FileUtils class
moveDirectory(File srcDir, File destDir) we can move whole directory
If a File object points to a folder you can iterate over it's content
File dir1 = new File("C:\\Users\\i074924\\Desktop\\Test");
if(dir1.isDirectory()) {
File[] content = dir1.listFiles();
for(int i = 0; i < content.length; i++) {
//move content[i]
}
}
Since Java 1.7 there is java.nio.file.Files which offers operations to work with files and directories. Especially the move, copy and walkFileTree functions might be of interest to you.
You can rename the directory itself.
You can iterate over files in directory and rename them one-by-one. If directory can contain subdirectories you have to do this recursively.
you can use utility like Apache FileUtils that already does all this.

Categories