I need to upload a Folder with sum x of .png files and save them into a hashmap. How can I achieve this. My thought was
HashMap<Integer,Image> map = new HashMap<>();
for (int i= map.size();map>0;map-- ){
map.put(i, new Image(new FileInputStream("C:\\Users\\drg\\Documents\\image"+i+".png")));
}
the problem is, in the beginning my HashMap contains 0 items, therefor it will always remain 0. So how can I add the .png files to my HashMap if I dont know how many .png files are in my folder.
Another problem is that I am using the FileInputStream and need to know the exact "name" of the .png file. How can I find out how many .png files there are and upload them into my HashMap without needing to know their exact filename?
All you need to do is list the contents of the folder and find the matching file names. E.g. using the java.nio
API and putting the images into a list:
Path folder = FileSystems.getDefault().getPath("Users", "drg", "Documents");
List<Image> images = Files.list(folder)
.filter(path -> path.getFileName().toString().matches("image\\d+\\.png"))
.map(Path::toUri)
.map(URI::toString)
.map(Image::new)
.collect(Collectors.toList());
Or using the old java.io
API:
File folder = new File("C:/Users/drg/Documents");
File[] imageFiles = folder.listFiles(file -> file.getName().matches("image\\d+\\.png"));
List<Image> images = new ArrayList<>();
for (File file : imageFiles) {
images.add(new Image(file.toURI().toString()));
}
If you need to index them by the integer, it's reasonably easy to extract that integer value when you have the filename.