KarlNorway
KarlNorway

Reputation: 55

Convert a file array to string array JAVA

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.

Upvotes: 1

Views: 12747

Answers (4)

Chenhai-胡晨海
Chenhai-胡晨海

Reputation: 1385

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();

Upvotes: 3

Shubhankar Raj
Shubhankar Raj

Reputation: 309

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

Upvotes: 1

Marv
Marv

Reputation: 3557

Use Files getName() method:

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

Upvotes: 0

AlexR
AlexR

Reputation: 115338

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

Upvotes: 9

Related Questions