代码缩短与while,for ,,,等?

问题描述 投票:-1回答:2

这段代码很乱,很长,这就是我无法轻易修改的原因。我尝试使用whilefor循环,等等,但我不能。你能不能帮我缩短它。非常感谢。

String path1 = "/storage/Folder/" + file_name;
String path2 = Environment.getExternalStorageDirectory().getPath() + "/Folder/" + file_name;
String path3 = Environment.getExternalStorageDirectory().getPath() + "/Folder2/" + file_name;

File file1 = new File(path1);
File file2 = new File(path2);
File file3 = new File(path3);

if (file1.exists()) {
    // do something 1
} else if (file2.exists()) {
    // do something 2
} else if (file3.exists()) {
    // do something 3
} else {
    // do something 4
}

我这样想;

String[] path_array = {path1, path2, path3};

for (String current_str : path_array) {
    File fi = new File(current_str);
    if (fi.exists()) {
        // do something
    }
}
android while-loop
2个回答
0
投票

如果你有流api,你可以像这样使用它:

List<File> files = new ArrayList<>();
files.add(new File("/"));
files.add(new File("/"));
files.add(new File("/"));

files.stream().filter(File::exists).forEach(f -> { /* do something */ });

否则你可以这样做:

List<File> files = new ArrayList<>();
files.add(new File("/"));
files.add(new File("/"));
files.add(new File("/"));

for (File file: files) {
    if(file.exists()) {
        //do something
    }
}

0
投票

循环用于重复性任务。由于您为每个文件“做某事”不同,因此您无需循环。您可以使用循环进行文件构建,但是您必须创建File对象数组以供以后访问。如果你想要易于理解的代码(不是更短的),你可以尝试这样的东西,但同样,你的代码很好。

public void yourCallingMethod() {
    if(!file1Exists && !file2Exists && !file3Exists) {
        // do something 4
    }
}

public boolean file1Exists(String file_name) {
    File file = new File("/storage/Folder/" + file_name);

    if (file.exists()) {
            // do something 1
        return true;
    }

    return false;
}

public boolean file2Exists(String file_name) {
    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Folder/" + file_name);

    if (file.exists()) {
            // do something 2
        return true;
    }

    return false;
}

public boolean file3Exists(String file_name) {
    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Folder2/" + file_name);

    if (file.exists()) {
            // do something 3
        return true;
    }

    return false;
}
© www.soinside.com 2019 - 2024. All rights reserved.