如何在编写Java外部库时访问文件
我正在编写一个小型Java库(例如项目A),将在任何其他项目(项目B)中在外部使用(作为.jar)。
这就是项目A的样子:
projectA
--src/main/java
--packageOne
....
--packageTwo
--A.java // need to access the next few text files in this java file
--ImportantTextOne.txt
--ImportantTextTwo.txt
--ImportantTextThree.txt
这就是项目B的外观:
projectB
--src/main/java
--B.java // I will use project A here.
我尝试导入文本文件,但是每次我将其用作projectb外部的.jar时,我总是会遇到一些错误
java.nio.file.nosuchfileException
我认为这是因为某些班级路径问题。
那么,如何在Projecta中正确读取文本文件?
预先感谢
编辑:我不需要ProjectB中的文本文件,它们仅用于从Projecta中摘取文本。我想要的只是在Projecta中正确读取这些文件,因此我可以在任何项目中导入Projecta而不会出现错误。
I am writing a small Java Library (say project A) to be used externally (as a .JAR) in any other project (project B).
This is how project A looks like :
projectA
--src/main/java
--packageOne
....
--packageTwo
--A.java // need to access the next few text files in this java file
--ImportantTextOne.txt
--ImportantTextTwo.txt
--ImportantTextThree.txt
This is how project B will look like :
projectB
--src/main/java
--B.java // I will use project A here.
I have tried importing the text files, but every time I use it as a .JAR externally in ProjectB, I always get some errors such as
java.nio.file.NoSuchFileException
I presume this is because of some class path issue.
So how do i correctly read my text files in ProjectA?
thanks in advance
Edit : I don't need the text files in projectB, they are just used once to pull text from in projectA. All I want is to correctly read those files in projectA, so I can import projectA in any project and not get errors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将TXT文件放置在类文件之外。您可能必须将它们移至
src/main/resources/packagetwo
对于您的构建过程,可以正确处理它们。无论如何,一旦构建JAR文件,请确保它们位于正确的位置。
要访问该文件,您无法从文件系统中加载它,因为它是JAR的一部分。但这在班级路径上。因此,您需要像
You placed the txt files besides the class files. You may have to move them to
src/main/resources/packageTwo
for your build process to correctly handle them. Anyway, make sure they are at the right location once the jar file is built.
To access such a file, you cannot load it from the filesystem as it is part of your jar. But it is on the classpath. So you need to access it like
因此,借助 hiran的响应 并进行挖掘(也 this )我弄清楚了。
您正在编写的库的文件结构:
每当阅读文件时,将其视为资源。就像当类用作外部.jar时,您将无法访问.jar内部的 。而是请按照这种类型的模式:
A.Java
So with the help of Hiran's response and digging around (also this) I figured it out.
File structure of the library you are writing :
Whenever reading a file, treat it as a resource. As when the class will be used as an external .JAR you will not be able to access files inside the .JAR. Instead follow this type of pattern :
A.java