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

Categories

0 votes
847 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...