Is there any way to show user, content of the .txt file directly stored in my jar application package (org/something/something.txt) without storing it on users pc or any temp. file ?I want to access it directly. Shoud i access it as a resource?Or as normal file?
Asked
Active
Viewed 129 times
5 Answers
2
You need to use the getResourceAsStream()
method to obtain an InputStream
.
Then, you can read the text by using BufferedReader
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("file.txt");
BufferedReader buf = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while((line = buf.readLine()) != null){
// something
}
Shoud i access it as a resource?Or as normal file?
In my limited knowledge, it depends. If you do not want the file to change at all, embed it into the jar. Else, keep it as a normal file on disk.
Do read this: Java resource as file
![](../../users/profiles/-1.webp)
Community
- 1
- 1
![](../../users/profiles/1894684.webp)
An SO User
- 23,378
- 30
- 119
- 197
-
1Thank you for answer and info.Worked well :) – Tomas Bisciak Nov 06 '13 at 16:10
1
Use something like that
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("file.txt");
![](../../users/profiles/2162924.webp)
Dario
- 1,963
- 17
- 29
1
No, do not retrieve the file as a resource. This will effectively prevent you from doing anything else with it. The content isn't loaded properly, which is all too indicative of trouble.
![](../../users/profiles/2961238.webp)
Joe
- 11
- 1
1
If the file is in src/org/something/something.txt
you can call it as follows
public static void main(String[] args) {
InputStream inputStream = null;
BufferedReader br = null;
try {
inputStream = AClassYouAreRunningThisFrom.class.getClassLoader().getResourceAsStream("org/something/something.txt");
br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
![](../../users/profiles/2835455.webp)
melc
- 11,373
- 2
- 30
- 39