MG97 MG97 - 2 months ago 6
Java Question

Iterating through array using for loop - keeps failing?

(Hello world level tester here)
I've got a java application to delete a bunch of files post tests to keep everything clean, however the issue is I can't seem to get it to work, this is my first time touching on an array and it's a slightly more complex one than the ones they show in the tutorials, any assistance would be greatly appreciated.

String[] fileArray;
fileArray = new String[8];

fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";

String home = System.getProperty("user.home");
File filePath = new File(home+fileArray);
System.out.println(filePath);

for (String count: fileArray) {
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(count);
}

Answer

try it this way

 String[] fileArray;
    fileArray = new String[8];

    fileArray[0] = "/Downloads/file1.csv";
    fileArray[1] = "/Downloads/file2.csv";
    fileArray[2] = "/Downloads/file3.csv";
    fileArray[3] = "/Downloads/file4.csv";
    fileArray[4] = "/Downloads/file5.csv";
    fileArray[5] = "/Downloads/file6.csv";
    fileArray[6] = "/Downloads/file7.csv";
    fileArray[7] = "/Downloads/file8.csv";

    String home = System.getProperty("user.home");
    //File filePath = new File(home+fileArray);  thats wrong here and will give you a invalid file anyway as you concatenating a string with an object


    for (String file: fileArray) {
    File filePath = new File(home+file); //here you need to define the file
    if (filePath.exists()) {
        filePath.delete();
        System.out.println("Deleted");
    }
    else
    {
        System.out.println("failed");
        Assert.fail();
    }
    System.out.println(file);
    }
Comments