简体   繁体   中英

java : collection <Object[]> : listfiles

I would like to set a collection of object using listfiles instead of doing this manually :

@Paramaters
public static Collection<Object[]> data()
{
     Object[][] data = new Object[][]{{"test_files/myfilea.txt"}, {"test_files/myfileb.txt"},{"test_files/myfilec.txt"},{"test_files/myfiled.txt"}};

return Arrays.asList(data);
}

Any idea, solution, please.

Do this

File theDirectory = new File("test_files");
File[] theFiles;
if(theDirectory.isDirectory()) 
    theFiles = theDirectory.listFiles();
else
    return null; //Or throw exception... up to you
List<Object[]> yourFilesList = new ArrayList<Object[]>();   //Edited here
for(File f: theFiles)
{
    if(f.isFile())
        //yourFilesList.add(new Object[]{f.getName()});       //Edited here again
        // or your code may rely on directory also so you can do this
         yourFilesList.add(new Object[]{"test_files/" + f.getName()}); 
}
return yourFilesList;

Something like this? If not please clarify.

public static Collection<File> data() {
    return Arrays.asList(new File("test_files").listFiles());
}

If you must have the array within a collection, try this:

public static Collection<Object[]> data() {
    return java.util.Collections.singleton((Object[])new File("test_files").listFiles());
}

Edit: One more try:

public static Collection<Object[]> data() {
    String[] fileNames = new File("test_files").list();
    Object[] namesInObjectArray = new Object[fileNames.length];
    for (int i = 0; i < fileNames.length; i++) {
        namesInObjectArray[i] = "test_files/" + fileNames[i];
    }
    Object[][] outerObjectArray = new Object[][] { namesInObjectArray };
    return Arrays.asList(outerObjectArray);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM