zoukankan      html  css  js  c++  java
  • How to get the file in a resource folder

    In a Maven project, we may often struggle to get a certain file (e.g. json file or sql file). Here is how to place the resource file and use it in the java class.

    1. If the main class is in folder src/main/java/, the resource file should be placed in the folder src/main/resources/

    Suppose the main class is GeneralTest.class and the file to be used is under src/main/resources/stories/simple-upgrades/retry-upgrade-file.story

    Then the java program should be as follows

    import java.io.File;
    import java.net.URISyntaxException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class GeneralTest {
    	
        protected String getStoriesDirectoryWithinResources() {
        	return "stories" + File.separator + "simple-upgrades";
        }	
        
        protected List<String> storyPaths() {
            List<String> result = new ArrayList<String>();
            String storiesDirectoryWithinResources = getStoriesDirectoryWithinResources();
            URL resource = GeneralTest.class.getClassLoader().getResource(storiesDirectoryWithinResources);
            System.out.println(resource);
            try {
                File folder = new File(resource.toURI());
                if (folder.exists() && folder.canRead() && folder.isDirectory()) {
                    File files[] = folder.listFiles();
                    Arrays.sort(files);
                    for (File file : files) {
                        result.add(file.getPath().substring(folder.getPath().lastIndexOf(storiesDirectoryWithinResources)));
                    }
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            return result;
        }
        
       public static void main(String... args) {
    		GeneralTest test = new GeneralTest();
    		System.out.println(test.storyPaths());
       }
    }
    

    The output should be:

    file:/home/username/workplace/JavaMavenPractice/target/classes/stories/simple-upgrades
    [stories/simple-upgrades/retry-upgrade-file.story]
    
  • 相关阅读:
    智能手机
    Micro LED
    paper-10-IRM-in-MANETs
    INFOCOM
    如何基于 Android Things 构建一个智能家居系统?
    (OK) VNCserver
    CCF 2016-04-2 俄罗斯方块
    CCF 2016-04-1 折点计数
    洛谷 P1927 防护伞
    洛谷 P1843 奶牛晒衣服
  • 原文地址:https://www.cnblogs.com/codingforum/p/4862347.html
Copyright © 2011-2022 走看看