I need check at least 4 directories if they exists and get the correct path in a variable for finnish my code.
But I don't know the correct way to do that.
Thanks for your help.
Here my code for check a single directory
final String uploadFilePath = "/mnt/sdcard/folder1/";
File f = new File(uploadFilePath);
if(f.exists() && f.isDirectory()){
Log.v("FILES", "EXIST");
}else{
Log.v("FILES", "DONT EXIST");
}
This way you can go on
String[] myDirectories = {"","",""......}; // your list of directories
for (String directory : myDirectories ) {
File file = new File(directory);
if(file.exists() && file.isDirectory())
// Do something you have found your directory
}
Is this enough?
Path uploadPath = Paths.get(uploadFilePath);
Path path = Files.exists(uploadPath) ? uploadPath : Files.createDirectory(uploadPath);
System.out.println(path);
Then to check for the N directories, put it in a loop maybe.
final String[] paths = { "C:/aa/", "C:/bb/", "C:/cc/", "C:/dd/"};
for (String path : paths) {
Path uploadPath = Paths.get(path);
if(Files.exists(uploadPath))
Files.createDirectory(uploadPath);
System.out.println(uploadPath);
}
Related
I have a folder called "all_users" in my java project under the src directory.How can I access the files(if there are any) in the all_users folder. I eventually want to loop through all the existing files in the "all_users" folder, comparing whether the file name is equal to a string i specify in the code.
Firstly, I tried File f = new File(System.getProperty("user.home")+File.pathSeparator + "all_users"); as the file object then later tried File dir = new File(TEST_PATH); Both returned false when i checked if it existed so i didn't set up the path correctly?
public class ValUtility {
static final String TEST_PATH = "./all_users/";
public static boolean validUsername(String user) {
File f = new File(System.getProperty("user.home") + File.pathSeparator + "all_users");
File dir = new File(TEST_PATH);
File[] directoryListing = f.listFiles();
System.out.println(f.exists());
System.out.println(directoryListing);
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
// think child is filename?
if (user.equals(child.getName())){
return false;
}
}
}
return true;
}
}
Please run...
System.out.println(System.getProperty("user.home"));
The above will inform you where you need to add a folder labeled 'all_users'. It is very unlikely that your 'user.home' property is set to your project's source file (src) folder.
I am facing issues when trying to ignore files with.db extension placed in folder location(say (\test\folder) using below java code.The code on execution is not working as expected and the files containing .db extension isn't ignored [which is what we are looking at in our requirement].
Please advice what changes or missing points are there in the below enlisted code.
I have pasted the code snippet causing trouble and not ignoring the file of .db extension.
String mess1 = "";
String mess2 = "";
String ext = "Thumbs.db";
Boolean result = false;
try{
File folder = new File(folderPath);
System.out.println(folder);
if(folder.exists()){
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0){
for(int i=0;i<listOfFiles.length;i++){
String name= listOfFiles[i].toString();
if(name.equalsIgnoreCase(ext)){
out.println(name);
result = false;
}
}
}
}
File.toString() does not do what you probably expect it to do. It returns the pathname string of this abstract pathname, not the name of the file.
Try File.getName() instead.
You should use file.getName() instead of file.toString() to abtain the name of the file and not the pathname.
Then you should use name.matches() instead of name.equals() to obtain all the files that have .db extension and not only the one with the name Thumbs.db
Please try below code which will print files ending with .db extension.
String mess1 = "";
String mess2 = "";
String ext = ".db";
Boolean result = false;
try{
File folder = new File("C:/FTP/");
System.out.println(folder);
if(folder.exists()){
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0){
for(int i=0;i<listOfFiles.length;i++){
String name= listOfFiles[i].getName();
if(name.endsWith(ext))
{
System.out.println(name);
result = false;
}
}
}
}
}catch(Exception e) {}
I have a class whose constructor receives a relative resources path (language properties files) and the corresponding classloader (the path is relative to the package of the classLoader):
public Language(String relDir, ClassLoader classLoader) {
...
}
Whithin that class I have a method that loads all found resource files (properties files such as MyFile_en_GB.properties), and it doesn't know whow many language resources there will be beforehand. It uses languagesDir as an absolute path for finding the resources.
private void loadLanguages() {
DirectoryStream.Filter<Path> filter = (path) -> {
return Files.isRegularFile(path) & path.getFileName()toString().startsWith("MyFile");
};
try (DirectoryStream<Path> stream = Files.newDirectoryStream(languagesDir, filter)) {
for (Path entry : stream) {
String fileName = entry.getFilename().toString();
...
loadPropertiesFile(filename)
}
} catch (..) {}
}
There, languagesDir works with an absolute path. However, when I tried:
String dir = classLoader.getResource(relDir).toString();
it throws an exception. I guess it is because it expects a file and not a directory
How can I get the absolute path of the resources? Should I try another aproach and work only with relative paths (how to do this)?
edit: About the exception:
classLoader.getResource(relDir) gives a null URL
try to use resourceFile.getName() after change URL to file.
URL resourceURL = classLoader.getResource(..);
File resourceFile = new File(new URL(resourceURL).toURI());
String fullPath = resourceFile.getName();
it throws an exception. I guess it is because it expects a file and
not a directory
If that is the case you can feed files instead directory. To get the absolute path you try as below
String dirPath = "C:\\Softwares";
File dir = new File( dirPath );
for ( String fileName : dir.list() ) {
File file = new File( dirPath + "\\" + fileName );
if ( file.isFile() ) {
// System.out.println( file.getAbsolutePath() );
String dir = classLoader.getResource( file.getAbsolutePath() ).toString();
}
}
I am using the NIO libraries but I am getting a strange error when I try to move files from one directory to another.
String yearNow = new SimpleDateFormat("yyyy").format(
Calendar.getInstance().getTime());
try {
DirectoryStream<Path> curYearStream =
Files.newDirectoryStream(sourceDir, "{" + yearNow + "*}");
//Glob for current year
Path newDir = Paths.get(sourceDir + "//" + yearNow);
if (!Files.exists(newDir) || !Files.isDirectory(newDir)) {
Files.createDirectory(newDir);
//create 2014 directory if it doesn't exist
}
}
Iterate over elements that start with "2014" and move them in the new directory (newDir, which is also called 2014)
for (Path p : curYearStream) {
System.out.println(p); //it prints out exactly the files that I need to move
Files.move(p, newDir); //java.nio.file.FileAlreadyExistsException
}
I get the java.nio.file.FileAlreadyExistsException because my folder (2014) already exists. What I actually want to do is move all the files that start with "2014" INSIDE the 2014 directory.
Better not going back to java.io.File and using NIO instead:
Path sourceDir = Paths.get("c:\\source");
Path destinationDir = Paths.get("c:\\dest");
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)) {
for (Path path : directoryStream) {
System.out.println("copying " + path.toString());
Path d2 = destinationDir.resolve(path.getFileName());
System.out.println("destination File=" + d2);
Files.move(path, d2, REPLACE_EXISTING);
}
} catch (IOException ex) {
ex.printStackTrace();
}
Files.move is not equivalent to the mv command. It won't detect that the destination is a directory and move files into there.
You have to construct the full destination path, file by file. If you want to copy /src/a.txt to /dest/2014/, the destination path needs to be /dest/2014/a.txt.
You may want to do something like this:
File srcFile = new File("/src/a.txt");
File destDir = new File("/dest/2014");
Path src = srcFile.toPath();
Path dest = new File(destDir, srcFile.getName()).toPath(); // "/dest/2014/a.txt"
Continue with #Andrew's answer
If we use only Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING); then it will delete source directory because we only provide a directory path not an absolute path of a particular file. So it will also delete a source directory when operation will be done.
Let's say source path is /opt/src which contains a csv files and destination path is /opt/dst and I want to move all files from src to dst and I'm using Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING); this then it will move all the files to dst but it will delete a src directory after moving all files because we didn't provide an absolute path of a each file for src as well as dst. We should have to provide src path like /opt/src/foo.csv and dst path like /opt/dst/foo.csv then and then it will not delete a source directory.
DirectoryStream used to iterate over the entries in a directory. A directory stream allows for the convenient use of the for-each construct to iterate over a directory. So we get an absolute path for src and we use resolve method for resolving an absolute path for dst.
Please refer DirectoryStream for more information.
Try this code:
public class App
{
public void moveFromSourceToDestination(String sourceName,String destinationName)
{
File mydir = new File(sourceName);
if (mydir.isDirectory())
{
File[] myContent = mydir.listFiles();
for(int i = 0; i < myContent.length; i++)
{
File file1 = myContent[i];
file1.renameTo(new File(destinationName+file1.getName()));
}
}
}
public static void main(String [] args)
{
App app = new App();
String sourceName = "C:\\Users\\SourceFolder";
String destinationName = "C:\\Users\\DestinationFolder\\";
app.moveFromSourceToDestination(sourceName,destinationName);
}
}
Using java.io.File, its as simple as this:
File srcFile = new File(srcDir, fileName);
srcFile.renameTo(new File(destDir, "a.txt"));
I am trying to move a file from one directory to another using renameTo() in java, however renameTo doesnt work (doesnt rename and move the file). Basically, I want to delete the file in one first with same file name, then copy a file from anoter directory to the same location where I deleted the file originally, then copy the new one with same name.
//filePath = location of original file with file name appended. ex: C:\Dir\file.txt
//tempPath = Location of file that I want to replace it to file file without the file name. ex: C:\AnotherDir
int pos = filePath.indexOf("C:\\Dir\\file.txt");
//Parse out only the path, so just C:\\Dir
String newFilePath = filePath.substring(0,pos-1);
//I want to delete the original file
File deletefile = new File(newFilePath,"file.txt");
if (deletefile.exists()) {
success = deletefile.delete();
}
//There is file already exists in the directory, but I am just appending .tmp at the end
File newFile = new File(tempPath + "file.txt" + ".tmp");
//Create original file again with same name.
File oldFile = new File(newFilePath, "file.txt");
success = oldFile.renameTo(newFile); // This doesnt work.
Can you tell me what I am doing wrong?
Thanks for your help.
You need to escape the backslashes in the string literal: "C:\\Dir\\file.txt". Or use File.separator to construct the path.
Additionally, ensure newFile's path is constructed properly:
File newFile = new File(tempPath + File.separator + "file.txt" + ".tmp");
//^^^^^^^^^^^^^^^^
as the commments in the posted code (...ex: C:\AnotherDir) indicate that tempPath has no trailing slash character.
I have moved files to the destination directory and after moving deleted those moved files from source folder, in three ways, and at last am using the 3rd approach in my project.
1st approach:
File folder = new File("SourceDirectory_Path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
Files.move(Paths.get("SourceDirectory_Path"+listOfFiles[i].getName()), Paths.get("DestinationDerectory_Path"+listOfFiles[i].getName()));
}
System.out.println("SUCCESS");
2nd approach:
Path sourceDir = Paths.get("SourceDirectory_Path");
Path destinationDir = Paths.get("DestinationDerectory_Path");
try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)){
for (Path path : directoryStream) {
File d1 = sourceDir.resolve(path.getFileName()).toFile();
File d2 = destinationDir.resolve(path.getFileName()).toFile();
File oldFile = path.toFile();
if(oldFile.renameTo(d2)){
System.out.println("Moved");
}else{
System.out.println("Not Moved");
}
}
}catch (Exception e) {
e.printStackTrace();
}
3rd approach:
Path sourceDirectory= Paths.get(SOURCE_FILE_PATH);
Path destinationDirectory = Paths.get(SOURCE_FILE_MOVE_PATH);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDirectory)) {
for (Path path : directoryStream) {
Path dpath = destinationDirectory .resolve(path.getFileName());
Files.move(path, dpath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ex) {
ex.printStackTrace();
}
Happy Coding !! :)