andres
andres

Reputation: 169

Android - Check if a file exists just using a part of its name

I have car models that each model can contain one or more images. So I have named my images using this protocol: CarModel_id_Image_id where id is an unique number identifier.

I wonder if I could ask if "CarModel_id" exist?

here is some of my code:

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

Is there a way to do what I want? Thanks and sorry for my english.

Upvotes: 1

Views: 2755

Answers (2)

Maryam Azhdari
Maryam Azhdari

Reputation: 1319

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();
    }

}

and for call:

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");

Upvotes: 0

Zach
Zach

Reputation: 1964

First get all files in your directory, loop through them, and check if the id exists in the file names

   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
    }

Upvotes: 2

Related Questions