Reputation: 553
I am new to Java
.I am working on my previous post link.
I want to return specific extension(like .txt
) file names under directory.
For this,I wrote the following method with 2 arguments.
public void 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 requirments
String[] fileNames;
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());
}
}
}
}
Here I am facing 2 problems.
function return type.
Adding FileName into fileNames
Array.
How can I fix this.
Thanks.
Upvotes: 2
Views: 3757
Reputation: 8473
It is good to use List instead of array
Change your code like this
public void FileMoving()
{
//created object for Class
ExternalFileExecutions ExternalFileExecutionsObject=new ExternalFileExecutions();
//calling Method from class object
List<String> fileNames = ExternalFileExecutionsObject.ListOfFileNames("C:/Documents and Settings/mahesh/Desktop/InputFiles",".txt");
//to find out the length of list
System.out.println(fileNames.size());
}
public List<String> 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 requirments
List<String> fileNames = new ArrayList<String>();
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].getName());
}
}
}
return fileNames ;
}
Upvotes: 1
Reputation: 6183
You could use something like the following:
public List<String> ListOfFileNames1(final String directoryPath,
final String fileType) {
List<String> result = new ArrayList<String>();
// Creating Object for File class
File root = new File(directoryPath);
for (File f : root.listFiles()) {
if (f.isFile() && f.getName().endsWith(fileType)) {
result.add(f.getName());
} // if
} // for
return result;
} // ListOfFileNames1
public List<File> ListOfFileNames2(final String directoryPath,
final String fileType) {
// Creating Object for File class
File root = new File(directoryPath);
return Arrays.asList(root.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile()
&& pathname.getName().endsWith(fileType);
}
}));
} // ListOfFileNames2
Upvotes: 0
Reputation: 63955
I would usually prefer to return a File
instead of a String
. That way you don't have to create a new file each time you want to work with it and you can access for example the file name (.getName()
> foo.txt
) or the whole path (getPath()
> /dir/foo.txt
) depending on what you need.
File
already has a built-in filter functionality, either working on the file as String
(FileNameFilter
) or on the File
itself (FileFilter
). As above, I would prefer working on the File
.
Implementing a FileFilter
is pretty simple.
private static class ExtensionFilter implements FileFilter {
private final String extension;
public ExtensionFilter(String extension) {
// store ".TXT"
this.extension = "." + extension.toUpperCase(Locale.ROOT);
}
@Override
public boolean accept(File pathname) {
// return true if it is a file and it ends with .TXT
return pathname.isFile() && pathname.getName().toUpperCase(Locale.ROOT).endsWith(extension);
}
}
Now add some methods that use such a filter and you are pretty much done.
// internal method that lists files, converts them into a List and makes sure it does not return null
private static List<File> listFilesWithExtension(File directory, ExtensionFilter filter) {
File[] files = directory.listFiles(filter);
return files != null ? Arrays.asList(files) : Collections.<File>emptyList();
}
/** use like listFilesWithExtension(directory, "txt") */
public static List<File> listFilesWithExtension(File directory, String extension) {
return listFilesWithExtension(directory, new ExtensionFilter(extension));
}
/** lists only .txt files */
private static final ExtensionFilter TXT_FILES = new ExtensionFilter("txt");
public static List<File> listTxtFiles(File directory) {
return listFilesWithExtension(directory, TXT_FILES);
}
If you actually want a list / array of Strings you can convert it later via methods like
public static String[] getFileNamesFromFiles(List<File> files) {
String[] result = new String[files.size()];
for (int i = 0; i < files.size(); i++) {
File file = files.get(i);
result[i] = file.getName();
}
return result;
}
Upvotes: 0
Reputation: 691685
You want to return several String from your method. So it should return a String[] or a List<String>
, for example.
You also want to respect the Java naming conventions, so the method should be declared as:
public String[] listOfFileNames(String directoryPath, String fileType)
If you read the javadoc of java.io.File
, you'll notice that there is a method which does exactly that. You just need to pass a FilenameFilter
, which tells the methof which file names should be returned:
public String[] listOfFileNames(String directoryPath, final String fileType) {
return new File(directoryPath).list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(fileType);
}
});
}
This code above uses an anonymous inner class, which implements the FilenameFilter interface. Read the Java tutorial to learn about them.
Upvotes: 0
Reputation: 2931
public List<String> 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 requirments
List<String> fileNames = new ArrayList<String>();
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].getName());
}
}
}
return fileNames;
}
Upvotes: 0
Reputation: 6917
For return type change your first line to
public String[] ListOfFileNames(String directoryPath,String fileType)
As for adding an item in array, you might want to consider using ArrayList instead. Like so:
List<String> stringList = new ArrayList<String>();
stringList.add("string")
Upvotes: 0
Reputation: 12363
The return type should be String[]
or List<String>
you need to put every file name you encounter that fulfils your criteria into the list or array and return the same in the end.
In this part of the code
If you are using Arrays
String[] fileNames;
int count = 0;
if (listOfFiles[fileIndex].getName().endsWith(fileType))
{
fileNames[count] = listOfFiles[fileIndex].getName();
count++;
}
return fileNames;
The rest of the code remains same....
In case you want to do it Using List
List<String> fileNames = new ArrayList<String>();
if (listOfFiles[fileIndex].getName().endsWith(fileType))
{
fileNames.add(listOfFiles[fileIndex].getName());
}
return fileNames;
Upvotes: 1
Reputation: 308753
Try this:
public List<String> getListOfFileNames(String directoryPath, String fileType) {
List<String> result = new ArrayList<String>();
// add the code to loop over the director list and add them to the result
return result;
}
An even better solution would be to use the list()
method that's build into the File
class. Pass it a FilenameFilter
.
http://docs.oracle.com/javase/7/docs/api/
The best thing to do is reuse code rather than write it again.
Upvotes: 0