上传一组.png文件并保存到hashmap中

qojgxg4l  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(273)

我需要上传一个文件夹的总和x的.png文件,并保存到一个hashmap他们。我怎样才能做到这一点。我的想法是

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

问题是,一开始我的hashmap包含0项,因此它将始终保持为0。如果我不知道我的文件夹里有多少个.png文件,我怎么能把.png文件添加到我的hashmap中呢。
另一个问题是,我使用的是fileinputstream,需要知道.png文件的确切“名称”。我怎样才能知道有多少.png文件,并上传到我的hashmap而不需要知道它们的确切文件名?

m1m5dgzv

m1m5dgzv1#

您只需列出文件夹的内容并找到匹配的文件名。e、 g.使用 java.nio api并将图像放入列表中:

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

还是用旧的 java.io 应用程序编程接口:

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

如果需要按整数对它们进行索引,那么在有文件名时提取该整数值相当容易。

rxztt3cl

rxztt3cl2#

如果有帮助的话,您可以使用filechooser手动选择文件(比如使用gui),然后将它们加载到列表中,这样从列表到Map就更容易了?

private void uploadPhoto() {
FileChooser fileChooser = new FileChooser();
//Sets file extension type filters (Pictures)
fileChooser.getExtensionFilters().addAll
(new FileChooser.ExtensionFilter("Picture Files", ".jpg", ".png"));

//Setting initial directory (finds current system user)
File initialDirectory;
String user = System.getProperty("user.name"); //platform independent
List<File> selectedFiles;
try {
    initialDirectory = new File("C:\\Users\\" + user + "\\Pictures" );
    fileChooser.setInitialDirectory(initialDirectory);  
    selectedFiles = fileChooser.showOpenMultipleDialog(Main.stage);
} catch(Exception e) {
    initialDirectory = new File("C:\\Users\\" + user);
    fileChooser.setInitialDirectory(initialDirectory);
    selectedFiles = fileChooser.showOpenMultipleDialog(Main.stage);
}

相关问题