CameronOfoluwa CameronOfoluwa - 3 months ago 7
Java Question

Java - Get Names Of Files In Directory

How would I get the ".txt" from displaying?

File folder = new File("C:/Users/Camaloony/Desktop/Java Stuff/Python Home Control/Users/");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println(listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}





g.drawString(listOfFiles[0].getName(), 660, 395);


enter image description here

Thanks in advance for any help

Answer

If you want to get rid of the ".txt" when you call

 g.drawString(listOfFiles[0].getName(), 660, 395);

You can call the replace method on the string you get back from listOfFiles[0].getName() like so

g.drawString(listOfFiles[0].getName().replace(".txt", ""), 660, 395);

This is related to Remove part of string if you'd like to know more about the replace() method or you can check out https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)

Comments