In this tutorial, we’ll explore the differences between different methods of reading files in Java. We’ll compare the getResourceAsStream() method and the...
Use the getResourceAsStream() method to get the InputStream when reading a file from inside a jar file. ... .getClassLoader(). .getResourceAsStream(fileName)
loads resources using system class loader, it obviously fails because it does not see your JARs
Lifepaths.class.getResourceAsStream(...)
loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARsWhen invoking getResourceAsStream(name), the name must start with "/". I am not sure whether this is necessary, but I have problem without it
8 Temmuz 2023
235 kişi değerlendirdi
10 yorum
{"2_p1n":{"state":{"logo":{"href":"//yandex.com.tr","isForeign":true},"form":{"action":"/search","searchLabel":"Bul","hiddenInputs":[{"name":"lr","value":20815}]},"actions":{"advancedSearch":{"checked":false,"ariaLabel":"Gelişmiş arama"},"moreButtonProps":{"ariaLabel":"Daha fazla"},"cbir":{"name":"cbir","label":"Görsele göre arama","infoUrl":"//yandex.ru/promo/photosearch/index?source=landingdesk","isMacOS":false}},"userSection":{"loggedIn":false,"loginProps":{"loginUrl":"https://passport.yandex.com.tr/auth?retpath=%2F&origin=serp_desktop_auth_new","loginText":"Giriş yap","burgerAriaLabel":"Menü"}},"navigation":{"tabs":[{"id":"www","label":"Arama","url":"//yandex.com.tr","params":{"source":"tabbar"},"target":""},{"id":"images","label":"Görsel","url":"//yandex.com.tr/gorsel/search","params":{"text":"[$query]","noreask":"[$noreask]","nomisspell":"[$nomisspell]","parent-reqid":"[$reqid]","from":"tabbar"}},{"id":"video","label":"Video","url":"//yandex.com.tr/video/search","params":{"text":"[$query]","noreask":"[$noreask]","parent-reqid":"[$reqid]","from":"tabbar"}},{"id":"maps","label":"Haritalar","url":"//yandex.com.tr/harita","params":{"text":"[$query]","source":"serp_navig"}},{"id":"translate","label":"Çeviri","url":"//ceviri.yandex.com.tr","params":{"text":"[$query]","from":"tabbar"}}],"selectedTabId":"www"},"context":{"query":"getresourceasstream java","reqid":"1723936705352102-3031869566991201705-balancer-l7leveler-kubr-yp-vla-142-BAL","noreask":"1","lr":"20815","counters":{"type":"b","data":{"$header":"0_8y27z000","logo":"0_8y27z001","login":"0_8y27z003","usermenu":"0_8y27z004","market-cart":"0_8y27z006","more-button":"0_8y27z007","cbir":"0_8y27z008","$navigation":"0_8y27z009","item":"0_8y27z00i","tab-www":"0_8y27z00b","tab-images":"0_8y27z00d","tab-video":"0_8y27z00f","tab-maps":"0_8y27z00h","tab-translate":"0_8y27z00j"}}},"loggedIn":false,"baobab":{"parentNode":{"context":{"genInfo":{"prefix":"0_8y27w01-0-1"},"ui":"desktop","service":"web","reqid":"1723936705352102-3031869566991201705-balancer-l7leveler-kubr-yp-vla-142-BAL","fast":{"name":"header-desktop"}}}}},"type":"header-desktop"},"2_8y270":{"state":{"answersUrl":"https://stackoverflow.com/questions/16570523/getresourceasstream-returns-null#answers","type":"fact","tabsOptions":[{"id":"question","text":"Soru"},{"id":"bestAnswer","text":"En iyi yanıt"},{"id":"moreAnswers","text":"27 yanıt daha","shortText":"Daha fazla"}],"tabContents":{"question":{"construct":[{"type":"paragraph","content":[{"type":"text","content":"I'm loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:"}]},{"type":"code","content":[{"type":"text","content":[{"type":"text","content":"/src/initialization/Lifepaths.txt"}]}]},{"type":"paragraph","content":[{"type":"text","content":"My code loads a file by calling "},{"type":"code","content":[{"type":"text","content":"Class::getResourceAsStream"}],"isInline":true},{"type":"text","content":" to return a "},{"type":"code","content":[{"type":"text","content":"InputStream"}],"isInline":true},{"type":"text","content":". "}]},{"type":"code","content":[{"type":"text","content":[{"type":"text","color":"keyword","content":"public"},{"type":"text","content":" "},{"type":"text","color":"keyword","content":"class"},{"type":"text","content":" Lifepaths {"}]},{"type":"text","content":[{"type":"text","content":" "},{"type":"text","color":"keyword","content":"public"},{"type":"text","content":" "},{"type":"text","color":"keyword","content":"static"},{"type":"text","content":" "},{"type":"text","color":"name","content":"void"},{"type":"text","content":" execute() {"}]},{"type":"text","content":[{"type":"text","content":" System.out.println(Lifepaths.class.getClass()."}]},{"type":"text","content":[{"type":"text","content":" getResourceAsStream("},{"type":"text","color":"string","content":"\"/initialization/Lifepaths.txt\""},{"type":"text","content":"));"}]},{"type":"text","content":[{"type":"text","content":" }"}]},{"type":"text","content":[{"type":"text","content":""}]},{"type":"text","content":[{"type":"text","content":" "},{"type":"text","color":"keyword","content":"private"},{"type":"text","content":" Lifepaths() {}"}]},{"type":"text","content":[{"type":"text","content":""}]},{"type":"text","content":[{"type":"text","content":" "},{"type":"text","color":"comment","content":"//This is temporary; will eventually be called from outside"}]},{"type":"text","content":[{"type":"text","content":" "},{"type":"text","color":"keyword","content":"public"},{"type":"text","content":" "},{"type":"text","color":"keyword","content":"static"},{"type":"text","content":" "},{"type":"text","color":"name","content":"void"},{"type":"text","content":" main(String[] args) {execute();}"}]},{"type":"text","content":[{"type":"text","content":"}"}]}]},{"type":"paragraph","content":[{"type":"text","content":"The print out will always print "},{"type":"code","content":[{"type":"text","content":"null"}],"isInline":true},{"type":"text","content":", no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:"}]},{"type":"list","content":[{"type":"text","content":[{"type":"code","content":[{"type":"text","content":"\"/src/initialization/Lifepaths.txt\""}],"isInline":true}]},{"type":"text","content":[{"type":"code","content":[{"type":"text","content":"\"initialization/Lifepaths.txt\""}],"isInline":true}]},{"type":"text","content":[{"type":"code","content":[{"type":"text","content":"\"Lifepaths.txt\""}],"isInline":true}]}]},{"type":"paragraph","content":[{"type":"text","content":"Neither of these work. "},{"type":"text","content":"I've"},{"type":"text","content":"read"},{"type":"text","content":"numerous"},{"type":"text","content":"questions"},{"type":"text","content":" so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load "},{"type":"code","content":[{"type":"text","content":"filename"}],"isInline":true},{"type":"text","content":"), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name. "}]},{"type":"paragraph","content":[{"type":"text","content":"How do I solve this?"}]}],"footerProps":{"date":1580509310,"numLiked":265,"numCommented":9}},"bestAnswer":{"construct":[{"type":"paragraph","content":[{"type":"code","content":[{"type":"text","content":"Lifepaths.class.getClass().getResourceAsStream(...)"}],"isInline":true},{"type":"text","content":" loads resources using system class loader, it obviously fails because it does not see your JARs"}]},{"type":"paragraph","content":[{"type":"code","content":[{"type":"text","content":"Lifepaths.class.getResourceAsStream(...)"}],"isInline":true},{"type":"text","content":" loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs"}]},{"type":"paragraph","content":[{"type":"text","content":"When invoking getResourceAsStream(name), the name must start with \"/\". I am not sure whether this is necessary, but I have problem without it"}]}],"footerProps":{"date":1688829260,"numLiked":235,"numCommented":10}},"moreAnswers":[{"construct":[{"type":"paragraph","content":[{"type":"text","content":"The rules are as follows:"}]},{"isNumbered":true,"type":"list","content":[{"type":"text","content":[{"type":"text","content":"check the location of the file you want to load inside the JAR (and thus also make sure it actually added to the JAR)"}]},{"type":"text","content":[{"type":"text","content":"use either an absolute path: path starts at the root of the JAR"}]},{"type":"text","content":[{"type":"text","content":"use an relative path: path starts at the package directory of the class you're calling getResource/ getResoucreAsStream"}]}]},{"type":"paragraph","content":[{"type":"text","content":"And try:"}]},{"type":"code","content":[{"type":"text","content":[{"type":"text","content":"Lifepaths.class.getResourceAsStream("},{"type":"text","color":"string","content":"\"/initialization/Lifepaths.txt\""},{"type":"text","content":")"}]}]},{"type":"paragraph","content":[{"type":"text","content":"instead of"}]},{"type":"code","content":[{"type":"text","content":[{"type":"text","content":"Lifepaths.class.getClass().getResourceAsStream("},{"type":"text","color":"string","content":"\"/initialization/Lifepaths.txt\""},{"type":"text","content":")"}]}]},{"type":"paragraph","content":[{"type":"text","content":"(not sure if it makes a difference, but the former will use the correct ClassLoader/ JAR, while I'm not sure with the latter)"}]}],"footerProps":{"date":1368622980,"numLiked":72,"numCommented":4}},{"construct":[{"type":"paragraph","content":[{"type":"text","content":"So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently."}]},{"type":"paragraph","content":[{"type":"text","content":"The best explanation I have seen is this article from "},{"type":"text","content":"InfoWorld"},{"type":"text","content":". I'll summarize here, but if you want to know more you should check out the article."}]},{"type":"paragraph","content":[{"type":"text","content":"Methods"}]},{"isNumbered":true,"type":"list","content":[{"type":"text","content":[{"type":"code","content":[{"type":"text","content":"ClassLoader.getResourceAsStream()"}],"isInline":true},{"type":"text","content":"."}]}]},{"type":"paragraph","content":[{"type":"text","content":"Format: \"/\"-separated names; no leading \"/\" (all names are absolute)."}]},{"type":"paragraph","content":[{"type":"text","content":"Example: "},{"type":"code","content":[{"type":"text","content":"this.getClass().getClassLoader().getResourceAsStream(\"some/pkg/resource.properties\");"}],"isInline":true}]},{"isNumbered":true,"type":"list","content":[{"type":"text","content":[{"type":"code","content":[{"type":"text","content":"Class.getResourceAsStream()"}],"isInline":true}]}]},{"type":"paragraph","content":[{"type":"text","content":"Format: \"/\"-separated names; leading \"/\" indicates absolute names; all other names are relative to the class's package"}]},{"type":"paragraph","content":[{"type":"text","content":"Example: "},{"type":"code","content":[{"type":"text","content":"this.getClass().getResourceAsStream(\"/some/pkg/resource.properties\");"}],"isInline":true}]},{"type":"paragraph","content":[{"type":"text","content":"Updated Sep 2020: Changed article link. Original article was from Javaworld, it is now hosted on InfoWorld (and has many more ads)"}]}],"footerProps":{"date":1599825035,"numLiked":60,"numCommented":6}}]},"organic":{"faviconProps":{"src":"https://favicon.yandex.net/favicon/v2/https://stackoverflow.com","size":"m","pageNumber":0,"index":0},"title":"\u0007[getResourceAsStream\u0007] returns null","pathProps":{"items":[{"url":"https://stackoverflow.com/questions/16570523/getresourceasstream-returns-null","text":"stackoverflow.com"},{"url":"https://stackoverflow.com/questions/16570523/getresourceasstream-returns-null","text":"getresourceasstream-returns-null"}]},"faviconPosition":0,"subtitlePosition":1,"linkProps":{"url":"https://stackoverflow.com/questions/16570523/getresourceasstream-returns-null"},"hostTitle":"stackoverflow.com","description":""},"extralinksProps":{"hidden":true,"directions":["bottom-end"],"items":[{"variant":"reportFeedback","reportFeedback":{"feature":"Блок ответов для разработчиков","title":"Bu yanıtta yanlış olan nedir?","checkBoxLabels":[{"value":"Yanıt sorguya uygun değil"},{"value":"Yanıt hatalı"},{"value":"Yanıttaki bilgiler eksik"},{"value":"Diğer"}]}}]},"baobab":{"parentNode":{"context":{"genInfo":{"prefix":"2_8y27w0c-0-1"},"ui":"desktop","service":"web","reqid":"1723936705352102-3031869566991201705-balancer-l7leveler-kubr-yp-vla-142-BAL","fast":{"name":"article"}}}}},"type":"article"},"2_8y271":{"state":{"linksGroups":[{"type":"geo","links":[{"label":"Columbus","title":"Columbus","url":"//yandex.com.tr/tune/geo","logNode":{"name":"region"},"target":"_self","a11yLabel":"Bölgeniz Columbus","needRetpath":true}]},{"type":"feedback","links":[{"label":"Hata bildir","logNode":{"name":"feedback","attrs":{"behaviour":{"type":"dynamic"}}}}]},{"type":"settings","links":[{"label":"Ayarlar","url":"//yandex.com.tr/tune/search","logNode":{"name":"settings"},"target":"_self","needRetpath":true}]},{"type":"company","links":[{"label":"Hakkımızda","url":"https://company.yandex.com.tr","logNode":{"name":"about"},"target":"_blank"},{"label":"Ticari teklifler","url":"/search/direct?text=getresourceasstream%20java&filters_docs=direct_cm","logNode":{"name":"commercial"},"target":"_blank"},{"label":"Kariyer","url":"//yandex.com.tr/jobs/?utm_source=serp_turkie&utm_medium=footerlink&utm_content=career","logNode":{"name":"vacancy"},"target":"_blank"},{"label":"Kullanım lisansı","url":"//yandex.com.tr/legal/termsofuse/","logNode":{"name":"license"},"target":"_blank"},{"label":"Gizlilik Politikası","url":"//yandex.com.tr/legal/confidential/","logNode":{"name":"confidential"},"target":"_blank"}],"a11yHidden":true}],"reportFeedbackProps":{"feature":"Подвал","title":"Hata bildir","checkBoxLabels":[]},"isSearchApp":false,"hasExtralinks":true,"limitingSelector":".AliceFabButton","baobab":{"parentNode":{"context":{"genInfo":{"prefix":"2_8y27w0d-0-1"},"ui":"desktop","service":"web","reqid":"1723936705352102-3031869566991201705-balancer-l7leveler-kubr-yp-vla-142-BAL"}}}},"type":"serp-footer"},"2_8y272":{"state":{"conditionLoadList":{"marketCart":false,"highchartsHighstock":false,"advProductGallery":false,"musicPlayer":false,"ecomRates":false,"photoViewer":false,"easterEggModal":false,"easterEggPlusGamesModal":false,"darkmodeChangeDrawer":true},"reportFeedbackBaseProps":{"initEmail":"","metaFields":{"userAgent":"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)","userTestids":"186144,1071110,1028332,1078508,1047187,1054383,1075674,1078245,1081535,1079140,1084780,1075725,1086873,1074520,1083276,1086128,1083942,1086746,1088334,936723,1088671,1088688,1077211,1086083,66185,1084552,1086023,1089299,1082915,1087328,1060354,1079188,1085583,88927,1077691,1070801,40254,32737,461653,1079935,996797,1056315,1081489,45972,1080095,89889,151171,1079127,1069988,13963,287509,1073314,338390,785125,1081010,1083317,1079568,1083829,1071916,1081665,1087425,1087742,912288","yandexuid":"1111987371723936700","uid":"0","queryText":"getresourceasstream java","reqid":"1723936705352102-3031869566991201705-balancer-l7leveler-kubr-yp-vla-142-BAL","searchSlices":["drawer_search_slice_english","drawer_search_slice_cs"],"userRegionName":"Columbus","userRegionId":"20815","isChildAccount":false}},"extralinksPopupProps":{"abuseLink":"https://twitter.yandex.com.tr/search/abuse?sign=a5d520a119e8daf4f35d3bdd9a3bbb07&keyno=0"},"isLoggedIn":false,"userMenuDialogProps":{"flag":"skin,feedback","host":"yandex.com.tr","lang":"tr","project":"serp","queryParams":{"utm_source":"search"},"retpath":"https%3A%2F%2Ftwitter.yandex.com.tr%2Fsearch%3Fes_context%3D0oYmAQ____________ARpMMTcxOTc2MzI1NzQwMTAxNS0xODI4NjkzNjUwODEwMDQwMjQzMC1iYWxhbmNlci1sN2xldmVsZXIta3Vici15cC1rbGctMjgxLUJBTDIFYXNzb2PZ_-_n%26lr%3D20815%26noreask%3D1%26rq%3D1%26serp-reload-from%3Drec_bottom%26source%3Dtabbar%26text%3Dgetresourceasstream%2Bjava%26ncrnd%3D66331","tld":"com.tr"},"baobab":{"parentNode":{"context":{"genInfo":{"prefix":"2_8y27w0e-0-1"},"ui":"desktop","service":"web","reqid":"1723936705352102-3031869566991201705-balancer-l7leveler-kubr-yp-vla-142-BAL","fast":{"name":"lazy-load"}}}}},"type":"lazy-load"}}