1

I need some help.

I use this code to get the files in a folder as an array .

String fileDir = Directorty; File dir = new File(fileDir); FileFilter fileFilter = new WildcardFileFilter("*.html"); files = dir.listFiles(fileFilter); 

But I want to write a file with only the files in that folder and not the path. The result is:

[C:\Askeladden-17-12-2014\.html, C:\Askeladden-17-12-2014\barnetv.html, C:\Askeladden-17-12-2014\britiskebiler.html, C:\Askeladden-17-12-2014\danser.html, C:\Askeladden-17-12-2014\disipler.html, C:\Askeladden-17-12-2014\donald.html, C:\Askeladden-17-12-2014\ekvator.html, C:\Askeladden-17-12-2014\engelskspraak.html] 

But I want to have it without the path

C:\Askeladden-17-12-2014\ 

I have been looking around the webs to find some answers, but no luck. Using this:

strFiles = Arrays.toString(files); 

Gives a string presented as an array with [] in each end, and I am not able to get

strFiles.replace("C:\\Askleladden" + date +"\\", ""); 

to work.

4 Answers 4

9

You have to iterate the files array and call getName() for each file:

String[] names = new String[files.length]; for (int i = 0; i < files.length; i++) { names[i] = files[i].getName(); } 
Sign up to request clarification or add additional context in comments.

2 Comments

You will soon get to the harsh reality of StackOverflow @KarlNorway
@AlexR Its a figure of speache here in Norway. I know its not a trick but good coding ;)
3

Java 1.8, if you want get as List, just remove cast and to array

String[] files = (String[])Arrays.asList(dir.listFiles(filefilter)) .stream().map(x->x.getName()) .collect(Collectors.toList()) .toArray();

1 Comment

I get error when doing this. Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
1

Please find the solution below with proper comments.

import java.io.File; import java.io.FileFilter; public class fileNames { public static void main(String args[]){ //Get the Directory of the FOLDER String fileDir = "/MyData/StudyDocs/"; // Save it in a File object File dir = new File(fileDir); //FileFilter fileFilter = new WildcardFileFilter("*.html"); //Capture the list of Files in the Array File[] files = dir.listFiles(); for(int i = 0; i < files.length; i++){ System.out.println(files[i].getName()); } } } 

Comments

0

Use Files getName() method:

File file = new File("myFolder/myFile.png"); System.out.println(file.getName()); //Prints out myFile.png 

1 Comment

How will this work when there are several files in the folder.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.