[英]How do I load a text file in my program without it being located outside of the sources folder?
So up until now I can only get access to a text file in my java project by placing it outside of the sources folder and outside of any package.所以到目前为止,我只能通过将它放在源文件夹之外和任何包之外来访问我的 java 项目中的文本文件。 I don't think that's how it is supposed to be and I am wondering how else I can load the text file if I put it in a package?
我不认为它应该是这样的,我想知道如果我把它放在一个包中,我还能如何加载文本文件? Here's what I did for loading the text file, which worked but only since the file is located outside of the sources folder
这是我为加载文本文件所做的,它有效,但只是因为文件位于源文件夹之外
BufferedWriter bw = new BufferedWriter(new FileWriter("saveScores.txt")); //writing on it with a bufferedwriter
Scanner scan = new Scanner(new FileReader("saveData.txt")); //reading the data with a scanner
I would highly recommend to choose a distribution tool (Gradle, Maven, Ant...).我强烈建议选择一个分发工具(Gradle、Maven、Ant...)。 These Frameworks/Tools usually create destinct directories.
这些框架/工具通常会创建明确的目录。 For example a "source" or "src" directory, where your source code is supposed to live.
例如“source”或“src”目录,您的源代码应该存放在其中。 One of the other directories they will create is something like a "resource" or "res" directory, where static resources (like a ".txt" file) are supposed to live in.
他们将创建的其他目录之一类似于“resource”或“res”目录,静态资源(如“.txt”文件)应该存在于其中。
Distribution of software is not that trivial.软件的分发并不是那么简单。 You could do it all by your own, but I wouldn't recommed it.
你可以自己做这一切,但我不建议这样做。 You have to invest a little work to learn using one of these Frameworks/Tools if you want to distribute your code.
如果你想分发你的代码,你必须投入一些工作来学习使用这些框架/工具之一。 Choose wisely from the 3 top dogs in the Java world (Personal opinion: Choose Gradle):
从 Java 世界的 3 大狗中明智地选择(个人意见:选择 Gradle):
If you want to walk down that road to do it all by your self, follow best practises:如果您想自己走这条路,请遵循最佳实践:
getResourceAsStream
.getResourceAsStream
获取资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.