Android - 使用其名称的一部分检查文件是否存在

时间:2015-11-17 05:01:15

标签: android

我有车型,每个型号可以包含一个或多个图像。所以我使用这个协议命名我的图像:CarModel_id_Image_id 其中id是唯一的数字标识符。

我想知道我是否可以问“CarModel_id”是否存在?

这是我的一些代码:

File f = new File(Environment.getExternalStorageDirectory().getPath()
            + "/MyApp/Images/CarModel_" + id +"_");
if (f.exists()){
      /** some code here **/
}

有没有办法做我想要的?谢谢,抱歉我的英语。

2 个答案:

答案 0 :(得分:1)

首先获取目录中的所有文件,循环访问它们,然后检查文件名中是否存在id

   File f = new File(Environment.getExternalStorageDirectory().getPath()
            + "/MyApp/Images/");

   File[] files = f.listFiles();

    for (File file : files) {
                 //check if file name contains model number here using contains
                 //or split the string on underscore and check the id index
    }

答案 1 :(得分:0)

public static void writeToFile(String directory, String fileName,String fileNameNew, String data ) {   
File out = null;
OutputStreamWriter outStreamWriter = null;
FileOutputStream outStream = null;    
String LOG_DIR = "/MyLogFolder";
directory += LOG_DIR;
File dir = new File(directory);
out = new File(new File(directory), fileNameNew);

File f = new File(new File(directory).getPath());

    File[] files = f.listFiles();

    boolean existFile = false;

if (dir.exists()) {
        for (File file : files) {
            if (file.getName().contains(fileName)) {
                existFile = true;
                file.renameTo(out);
            }
        }
    }

if(!existFile) {
        try {
            out.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        outStream = new FileOutputStream(out,true);
        outStreamWriter = new OutputStreamWriter(outStream);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        assert outStreamWriter != null;
        outStreamWriter.append(data);
        outStreamWriter.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
try {
        assert outStreamWriter != null;
        outStreamWriter.append(data);
        outStreamWriter.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

并致电:

String date = Calendar.ShortDate.replace("/","-");
String time = Calendar.time.hours.toString() + "." + Calendar.time.minutes.toString();
Logger.writeToFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(),"MyLog","MyLog"+" "+date+" "+time+".txt","\n\n-------------\n"+"YourText");