0

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?

An SO User
  • 24,612
  • 35
  • 133
  • 221
Tomas Bisciak
  • 2,801
  • 5
  • 33
  • 57

5 Answers5

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

Community
  • 1
  • 1
An SO User
  • 24,612
  • 35
  • 133
  • 221
1

Use something like that

InputStream inputStream = 
        getClass().getClassLoader().getResourceAsStream("file.txt");
Dario
  • 2,053
  • 21
  • 31
1

Yes, you can store .txt files in .jar files.

Edit: Dario's answer.

slanecek
  • 808
  • 1
  • 8
  • 24
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.

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();
            }
        }
    }
    }
melc
  • 11,523
  • 3
  • 36
  • 41