How to get one file from a folder in java?

The idea is to take one file, but I do not want to list all 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 file name or the oldest file created in the folder

Has anyone ever tried to do this? Any ideas not to list all the files in the array and then take the first one?


Added:

Just in case, I was not clear (I am very sorry for my English. Please forgive me if I sound prepotent or aggressive, these are really not my intentions.) The file is not selected by the person, it is selected the machine does not request or will show the file, except for the method that returns a string with FileName

String findFileInFolder (String folderName)

As I comment on using ram and processor, because this is a secondary process, not the main project, so if I need to read more than a thousand files, this will significantly reduce the performance of my project :(

Thank;)


Update: the program runs on different computers, so if I could just access the directory without thinking about reading the file, that would be great. = D


Hope the latest update: sorry guys bother you :)

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

+3
source share
4

, , , .

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

  }

- , ;) , : D

+1

Java , . java 7, FileVisitor, .

0

, , :

import java.io.File;
import java.util.Arrays;
import java.util.Collections;

public class Shuffle {
   public static void main(String[] argv) 
   throws Exception {

      File dir = new File(".");
      String[] children = dir.list();
      Collections.shuffle(Arrays.asList(children));
      System.out.println(children[0]);
   }   
}
-1
source

Source: https://habr.com/ru/post/1757093/


All Articles