get file from dir java code example
Example 1: java get files in directory
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
Example 2: get file name from file path in java
package com.tutorialspoint;
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
File f1 = null;
String v, v1;
boolean bool = false;
try {
f = new File("C:\\test.txt");
f1 = new File("C:\\Program Files");
v = f.getName();
v1 = f1.getName();
bool = f.exists();
if(bool) {
System.out.println("File name: "+v);
}
bool = f1.exists();
if(bool) {
System.out.print("Folder name: "+v1);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}