Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

search File with same name but different extension Java

I parse a movies directory to get movie's title with the following code.

List<Movie> moviesList = new ArrayList<>();

   public String list(Request request, Response response) throws IOException {
       File file = new File("Z:\Films");
       File[] files = file.listFiles();
       for (int i = 0; i < files.length; i++) {
           Movie movie = new Movie(files[i].getName());
           moviesList.add(movie);
       }

Now I want to get a jpeg file with the same name which is in the same directory to display them on the web page. I don't know how to proceed..

I tried something like that with JK's idea(thanks again):

public String list(Request request, Response response) throws IOException {
        File file = new File("Z:\testApp");
        File[] files = file.listFiles();

        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().endsWith(".jpg") || files[i].getName().endsWith(".nfo") || files[i].getName().endsWith(".srt")) {
                continue;
            } else {
                String title = files[i].getName();
                File image = accept(files, title);
                Movie movie = new Movie(title, image);
                moviesList.add(movie);
            }
        }

    Map<String, Object> model = new HashMap<>();
            model.put("movies",moviesList);
        System.out.println(moviesList.get(0).getImage());


    createMovieListTxt();
            return Template.render("movies_list.html",model);
}

    public File accept(File[] files, String title) {
        File img = null;
        String[] split = title.split(" ");
        strVerif = split[0];
        for (int i = 0; i < files.length; i++) {
            String[] strings = files[i].getName().split(" ");
            if (strings[0].startsWith(strVerif) && files[i].getName().endsWith(".jpg")) {
                img = new File(files[i].getName());
                break;
            } else {
                continue;
            }
        }
        return img;
    }```
question from:https://stackoverflow.com/questions/65919907/search-file-with-same-name-but-different-extension-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could list the files again after your for loop and use a FilenameFilter.

file.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        //check if your movie list contains the name and if the extension matches
    }
});


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...