What is the difference between getResourceAsStream(“Words.txt”) and FileInputStream(“./src/package/Words.txt”)? [duplicate]

那年仲夏 提交于 2019-12-04 06:58:30

问题


I am currently writing a servlet based application (the client side). I tried to get a text file inside the same package where the code is located. All of the methods that I have come across used either MyClass.class.getResourceAsStream("Words.txt") or classLoader.getResourceAsStream("Words.txt") to get the text file (eg: SO1, SO2). But I have tried FileInputStream("./src/package/Words.txt") and the text file can still be successfully loaded.

What are the differences? And why is the method getResourceAsStream encouraged?


回答1:


At the moment, you're on your developer workstation, and are probably running your app from your IDE. Tomcat happens to be started from the IDE project root directory, and thus using

new FileInputStream("./src/package/Words.txt")

allows reading the file stored in your project src directory.

But that's not how the project will be run in production. In production, you'll have a Tomcat server started from a totally different directory, using a shell script. And the production server won't have the source project at all. All it will have is Tomcat, and the war file constituting the artifact built from the project.

So there will be no src directory at all, and the file Words.txt won't even be anywhere on the file system. It will only be en entry of the war file (which is in fact a zip file), located under WEB-INF/classes/package along with the .class files produced by the compiler from your Java source files.

So, in order to be able to read that "file", you can't use file IO: the "file" doesn't exist in the file system. You need to use the ClassLoader that will locate the "file" inside the war file and load it from there.

That will also go fine during development, when the app is run from an exploded war structure: the class loader will find the class under the target directory used by your IDE to store the class files and resource files.

Note that what you need to load that resource, if it's in the package com.foo and MyClass is in that same package, is

MyClass.class.getResourceAsStream("Words.txt") 

or

AnyOtherOfYourClassesWhateverThePackageIs.class.getResourceAsStream("/com/foo/Words.txt") 

or

classLoader.getResourceAsStream("com/foo/Words.txt")


来源:https://stackoverflow.com/questions/35501228/what-is-the-difference-between-getresourceasstreamwords-txt-and-fileinputstr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!