How to get a single file from a folder in java?

12,771

Solution 1

I decidee to use this code, is not exactly what I wanted but it works for now.

  public static String getFileToCrawl(String directory){
      File dir = new File(directory);

      String[] children = dir.list();
      if (children == null) {
          return "";
      } else {
          int i=0;
          String filename = children[i];
          while (i<children.length && !filename.contains(".txt")){
              i++;
              filename = children[i];
          }
          return filename;
      }

  }

if anyone like it or know a way to improve this code it's really welcome ;) if you want to use it feel free :D

Solution 2

You can have a look on FileFilter class and on the public File[] listFiles(FileFilter filter)

Using this method you will be able to filter files according to their last modification date for example.

On a side note, why do you want to avoid to list all the files, for performances concerns ?

Share:
12,771
Saikios
Author by

Saikios

merge me

Updated on June 04, 2022

Comments

  • Saikios
    Saikios almost 2 years

    The idea is to take one single file, but I don't want to list all of the files. I have the address of the specified folder, but not the name.

    Basically I want

    findFileInFolder(String folderName) --- this method returns a random filename or the oldest file created on the folder

    Has anybody ever tried doing this? Any ideas to avoid listing all of the files in an array and then taking the first one?


    Added:

    Just in case I wasn't clear (I'm really sorry for my English. Please forgive me if I sound prepotent or aggressive it is really not my intentions.) The file is not selected by a human, it's selected by the machine without asking or showing the file except for the method that returns a string with the FileName

    String findFileInFolder(String folderName)

    Like I comment is for usage of ram and processor because this is a secondary process and not the primary of the project, so if I have to read over a thousand files it will considerably reduce the performance of my project :(

    Thanks ;)


    Update: the program is running on different computers so if I could just access the directory not "thinking" about reading which file it would be great. =D


    Hopefully last update: sorry for bothering you guys :)

    From what I read on the answers there is no way. My question is: what good alternatives instead of doing an array would you think? My idea is to create an index in a textfile and to take only the first line.