Expected:
find the number files in the folder, and collect the absolute path for each file in the directory.
File certificatePath = new File("resources/NPL");
String absolutePath = certificatePath.getAbsolutePath();
File directory = new File(absolutePath);
int fileCount=directory.list().length;
From the above code getting the no of files in folder (resources/NPL), now i'm struggle to get the absolute path for the files.
You should use listFiles instead fo list() (provided you have the security rights to do so), otherwise you are stuck with the file names.
Well first of all what does it mean to collect it? If you need the file names it is already there for you in an array of String[] which you get from directory.list() method. If you want the full names you can use listFiles() method which returns a File[] and each file has getAbsolutePath() method. Something like:
for (File file : directory.listFiles()) {
System.out.println(file.getAbsolutePath());
}
Related
I have a HashSet of Strings, which are names of files that I want to copy from the working direcorory to the "path" directory. I find that the following piece of code should be working, however, I get a java.nio.file.NoSuchFileException: /commits/1/hello.txt exception.
Hashset<String> stagedQueue = HashSet<String>();
stagedQueue.put("hello.txt");
stagedQueue.put("bye.txt");
String path = "/commits/" + commitID;
for (String file : stagedQueue) {
Files.copy((new File(file).toPath()),
(new File(path + "/" + file).toPath()));
What can I do to fix this? I can't figure out why I am getting these exceptions. Please note that I am moving these into an empty directory.
Don't go through File; you use java.nio.file.
Your problem here is that you try and copy your initial file into a directory which does not exist yet:
String path = "/commits/" + commitID;
First of all, this is the destination directory, so call it dstdir, for instance. Then create the base directory and copy the files into it:
final Path basedir = Paths.get("/commits", commitId);
Files.createDirectories(basedir);
for (final String file: baseQueue)
Files.copy(Paths.get(file), basedir.resolve(file));
I have like 2 files with almost same name like "myfile_1234.mp4" and "myfile_5678.mp4" in the same directory. One File, say, "myfile_1234.mp4" size is ZERO bytes where as the other file say "myfile_5678.mp4" has some size NOT EQUAL to ZERO (say 32kb). Now I want to delete the 1st File from the Directory but not the other File.
Can we have something like a loop temp pointer to the Files in the Directory and we would then check for Size of file and delete it when its size is ZERO.
Can anyone help me here...?
This is a relatively straightforward exercise. Here are the things that you need to know to do understand what to do:
A directory is represented by a File object. Create a File object for the directory that you want to list
The listFiles() call produces an array of all files in the directory
The length() method returns the size of the file
The delete() method deletes the file
Your code will look like this:
// Reference the directory in which the files reside
File dir = new File("c:/my/test/directory");
// Go through the files in the directory in a loop
for ( File file : dir.listFiles()) {
// Make sure that an entry is a file (it could be a directory)
// and that its size is zero
if (file.isFile() && file.length() == 0) {
// If both conditions are true, delete the empty file
file.delete();
}
}
You can make additional conditions to check if a file has a particular name, extension, etc.
You can have a file (handle) created like
File myFileOne = new File(path);
File myFileTwo = new File(anotherPath);
Having such handles it is quite easy to check files size or names and delete the files as well. For more info on Java File see: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#File
I need to hold in memory all absolute paths of file names under a given directory.
myDirectory.list() - retrieves String[] of file names only (without their absolute paths).
Don't want to use File Object since it consumes more memory.
Last thing - I can use apache collections etc. (but didn't find anything useful for that).
String directory = <your_directory>;
File[] files = new File(directory).listFiles();
for(File file : files){
if(file.isFile()){
System.out.println(file.getAbsolutePath());
}
}
This works, and I gotta say I'm confused when you say you don't wanna use File objects, but whatever works, I guess.
Doesn't myDirectory holds the directory of all those files?
If so, just combine the path in myDirectory with each of the cells in the array myDirectory.list() returns.
I build java web Application.
I wrote 1 function in my class with 2 argument.If you pass directory path(where .txt files are saved) and filetype as a arguments to that function.It returns all the filenames,which files have with specified file extension.
public List<File> ListOfFileNames(String directoryPath,String fileType)
{
//Creating Object for File class
File fileObject=new File(directoryPath);
//Fetching all the FileNames under given Path
File[] listOfFiles=fileObject.listFiles();
//Creating another Array for saving fileNames, which are satisfying as far our requirements
List<File> fileNames = new ArrayList<File>();
for (int fileIndex = 0; fileIndex < listOfFiles.length; fileIndex++)
{
if (listOfFiles[fileIndex].isFile())
{
//True condition,Array Index value is File
if (listOfFiles[fileIndex].getName().endsWith(fileType))
{
//System.out.println(listOfFiles[fileIndex].getName());
fileNames .add(listOfFiles[fileIndex]);
}
}
}
return fileNames;
}
I tested this function in the following 2 ways.
Case 1:
I created folder name as InputFiles on my desktop and placed .txt files under InputFiles folder.
I pass directoryPath and .txt as a arguments to my function in the following way.It's working fine.
classNameObject.Integration("C:/Documents and Settings/mahesh/Desktop/InputFiles",".txt");
Case 2:
Now I placed my InputFiles folder under src folder and pass directoryPath as a argument in the following way.it's not working.
classNameObject.Integration("/InputFiles",".txt");
Why I am trying case 2,If I want to work on same Application in another system,everytime I don't need to change directorypath.
At deployment time also case 2 is very useful because,we don't know where will we deploy Application.so I tried case 2 it's not working.
It's working,when I mention absolute path.If I mention realPath it's not working.
How can I fix this.
can you explain clearly.
I hope, you understand why I am trying case 2.
Thanks.
well you can always user property class. Just set the path in property file and get that property by name in your class. Also if you ever feel like that you need to change the path mentioned in property file, it will get reloaded as soon as you make change in it.
The code basically allows the user to input the name of the file that they would like to delete which is held in the variable 'catName' and then the following code is executed to try and find the path of the file and delete it. However, it doesn't seem to work, as it won't delete the file this way. Is does however delete the file if I input the whole path.
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
If you're deleting files in the same directory that the program is executing in, you don't need specify a path, but if it's not in the same directory that your program is running in and you're expecting the program to know what directory your file is in, that's not going to happen.
Regarding your code above: the following examples all do the same thing. Let's assume your path is /home/kim/files and that's where you executed the program.
// deletes /home/kim/files/somefile.txt
boolean result = new File("somefile.txt").delete();
// deletes /home/kim/files/somefile.txt
File f = new File("somefile.txt");
boolean result = new File(f.getCanonicalPath()).delete();
// deletes /home/kim/files/somefile.txt
String execPath = System.getProperty("user.dir");
File f = new File(execPath+"/somefile.txt");
f.delete();
In other words, you'll need to specify the path where the deletable files are located. If they are located in different and changing locations, then you'll have to implement a search of your filesystem for the file, which could take a long time if it's a big filesystem. Here's an article on how to implement that.
Depending on what file you want to delete, and where it is stored, chances are that you are expecting Java to magically find the file.
String catName = 'test'
File file = new File(catName + '.txt');
If the program is running in say C:\TestProg\, then the File object is pointing to a file in the location C:\TestProg\test.txt. Since the file object is more of just a helper, it has no issues with pointing to a non-existent file (File can be used to create new files).
If you are trying to delete a file that is in a specific location, then you need to prepend the folder name to the file path, either canonically, or relative to the execution location.
String catName = 'test'
File file = new File('myfiles\\'+ catName +'.txt');
Now file is looking in C:\TestProg\myfiles\test.txt.
If you want to find that file anywhere, then you need a recursive search algorithm, that will traverse the filesystem.
The piece of code that you provided could be compacted to this:
boolean success = new File(catName + ".txt").delete();
The success variable will be true if the deletion was successful. If you do not provide the full absolute path (e.g. C:\Temp\test for the C:\Temp\test.txt file), your program will assume that the path is relative to its current working directory - typically the directory from where it was launched.
You should either provide an absolute path, or a path relative to the current directory. Your program will not try to find the file to delete anywhere else.