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)
The method getResourceAsStream() returns A java.io.InputStream object; null if no resource with this name is found, the resource is in a package that is not...
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_2fox":{"state":{"form":{"action":"/search","searchLabel":"Bul","hiddenInputs":[{"name":"lr","value":20815}],"logo":{"href":"//yandex.com.tr","isForeign":true,"size":40}},"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":"1724001037387123-14448684637742230450-balancer-l7leveler-kubr-yp-vla-56-BAL","noreask":"1","lr":"20815","counters":{"type":"b","data":{"$header":"0_1czrz000","logo":"0_1czrz001","login":"0_1czrz003","usermenu":"0_1czrz004","market-cart":"0_1czrz006","more-button":"0_1czrz007","cbir":"0_1czrz008","$navigation":"0_1czrz009","item":"0_1czrz00i","tab-www":"0_1czrz00b","tab-images":"0_1czrz00d","tab-video":"0_1czrz00f","tab-maps":"0_1czrz00h","tab-translate":"0_1czrz00j"}}},"loggedIn":false,"baobab":{"parentNode":{"context":{"genInfo":{"prefix":"0_1czrw01-0-1"},"ui":"desktop","service":"web","reqid":"1724001037387123-14448684637742230450-balancer-l7leveler-kubr-yp-vla-56-BAL","fast":{"name":"header-desktop"}}}}},"type":"header-desktop"},"2_1czr0":{"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_1czrw0c-0-1"},"ui":"desktop","service":"web","reqid":"1724001037387123-14448684637742230450-balancer-l7leveler-kubr-yp-vla-56-BAL","fast":{"name":"article"}}}}},"type":"article"},"2_1czr1":{"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_1czrw0d-0-1"},"ui":"desktop","service":"web","reqid":"1724001037387123-14448684637742230450-balancer-l7leveler-kubr-yp-vla-56-BAL"}}}},"type":"serp-footer"},"2_1czr2":{"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,1070958,66181,1078471,1000277,1054383,1075673,1078244,1081535,1079140,1084710,1075723,1086873,1074523,1083275,614106,1090449,936724,1088672,1088687,132354,1076737,1084554,1003071,1079234,963712,1071646,1082915,1083569,1081016,1021600,1066329,1079187,1085584,1087989,1087548,1077693,30278,1,1088226,965705,766162,284407,63006,1080095,46451,151171,1079127,287509,220488,1088995,338390,1081010,1084229,1088401,1080657,1080821,1081664,1087425,1083873","yandexuid":"9422304501724001037","uid":"0","queryText":"getresourceasstream java","reqid":"1724001037387123-14448684637742230450-balancer-l7leveler-kubr-yp-vla-56-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=61939218113aac73832fa16d2a9d4e0a&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%3Flr%3D20815%26noreask%3D1%26rnd%3D26709%26rq%3D1%26serp-reload-from%3Drec_bottom%26source%3Dtabbar%26text%3Dgetresourceasstream%2Bjava%26ncrnd%3D546","tld":"com.tr"},"baobab":{"parentNode":{"context":{"genInfo":{"prefix":"2_1czrw0e-0-1"},"ui":"desktop","service":"web","reqid":"1724001037387123-14448684637742230450-balancer-l7leveler-kubr-yp-vla-56-BAL","fast":{"name":"lazy-load"}}}}},"type":"lazy-load"}}