如何将Array Values作为输出返回给Java中的Method [英] How to return Array Values as a output to a Method in Java
本文介绍了如何将Array Values作为输出返回给Java中的Method的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Java
的新手。我正在处理上一篇文章 link 。
I am new to Java
.I am working on my previous post link.
我想返回特定的扩展名(如 .txt
)目录下的文件名。
I want to return specific extension(like .txt
) file names under directory.
为此,我用2个参数编写了以下方法。
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());
}
}
}
}
这里我遇到了2个问题。
Here I am facing 2 problems.
-
函数返回类型。
function return type.
将FileName添加到 fileNames
数组。
Adding FileName into fileNames
Array.
我该如何解决这个问题。
How can I fix this.
谢谢。
推荐答案
最好使用List而不是数组
像这样改变你的代码
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 ;
}
这篇关于如何将Array Values作为输出返回给Java中的Method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文