我想使用listfiles设置对象集合,而不是手动执行此操作:
@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);
}
任何想法,解决方案,请。
答案 0 :(得分:2)
这样做
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;
答案 1 :(得分:1)
这样的东西?如果没有请澄清。
public static Collection<File> data() {
return Arrays.asList(new File("test_files").listFiles());
}
如果您必须在集合中包含该数组,请尝试以下方法:
public static Collection<Object[]> data() {
return java.util.Collections.singleton((Object[])new File("test_files").listFiles());
}
编辑:再试一次:
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);
}