I have a folder in a directory. I know, there is always only one file and it's a .txt file. But I don't know the filename. How can I access it in Java? How must the path look like?
Asked
Active
Viewed 1,130 times
2 Answers
2
You could open the directory and go over its contents until you find the file:
public static File getTextFileInDirectory(String dirPath) {
File dir = new File(dirPath);
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().endsWith(".txt")) {
return f;
}
}
return null;
}
EDIT:
Based on the comments below, if it's safe to assume the directory always has a file in it, and there's nothing else in the directory (e.g., subdirectories), this code can be greatly simplified:
public static File getTextFileInDirectory(String dirPath) {
return new File(dirPath).listFiles()[0];
}

Mureinik
- 297,002
- 52
- 306
- 350
-
It was stated that the folder only contains that one file, so could just check the list is not empty and return the first file – OneCricketeer Jul 17 '16 at 16:41
-
@cricket_007 I'm not sure about the interpretation of "there is always only one file and it's a .txt file." Does this mean that the file is the only thing in the directory, or that it's the only **file** and the directory could contain other things as well (e.g., subdirectories). – Mureinik Jul 17 '16 at 16:43
-
-
@Tobi123 in that case, I've over-complicated things, I you could do this with considerably less code. See my edited answer. – Mureinik Jul 17 '16 at 16:50
1
Since you know there will only be one file in the directory, you can get an array of the directory's files and return the first element if it exists, or null if it doesn't.
public static File getFileFromDir(File directory) {
File[] dirFiles = directory.listFiles();
return dirFiles.length > 0 ? dirFiles[0] : null;
}

SamTebbs33
- 5,507
- 3
- 22
- 44