Results 1 to 15 of 15
Like Tree3Likes
  • 1 Post By Fubarable
  • 1 Post By Raigeki
  • 1 Post By Tolls

Thread: Read from .txt file inside Jar

  1. #1
    Raigeki is offline Nocturnal Beast
    Join Date
    Jan 2013
    Posts
    8
    Rep Power
    0

    Default Read from .txt file inside Jar

    I have been studying Java for some time now and I have already made several programs, but now I'm stuck on a problem.
    I am trying to make the program read a text file inside the Jar, and after a quick Google search, I ended in this thread - Credits to csharp100.
    The code is in the bottom of the post.

    I messed around with it for a couple minutes trying to figure out how it works for one of my own programs but I just can't seem to make it read from a text file INSIDE the Jar. It works if I put the text file somewhere on the computer though. I have tried changing the path the BufferedReader is trying to access the file through(line 37) but nothing seems to work. When I try to read it as a resource with

    Java Code:
    getResourceAsStream( /resource address/ );
    it says "A non-static variable cannot be referenced from a static context". Do I have to add/remove "static" somewhere to fix it or is it because it's wrong to use "getResourceAsStream" in this code? Do I have to add the words from the .txt file to a java class instead and refer to it in the main class? I just can't seem to understand what the problem with the original code is. It compiles and runs perfectly without errors, but there is no way it can access text files from inside the Jar. I have been Googling my problem for days and nothing seems to fix it.

    Java Code:
    import java.io.*;
    import java.util.*;
     
    public class Unscrambler {
     
     
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		Scanner input = new Scanner(System.in);
    		System.out.print("Enter a word: ");
    		String str1 = input.nextLine();
    		char[] arrayOfChar1 = str1.toCharArray();
     
    		int i = str1.length();
     
    		String str2 = "/abcdefghijklmnopqrstuvwxyz";
    		char[] arrayOfChar2 = str2.toCharArray();
     
    		int[] arrayOfInt1 = new int[27];
    		int[] arrayOfInt2 = new int[27];
     
    		for (int j = 1; j < 27; j++) {
    			arrayOfInt1[j] = 0;
    		}
     
    		for (int j = 0; j < i; j++) {
    			for (int k = 1; k < 27; k++) {
    				if (arrayOfChar1[j] != arrayOfChar2[k])
    					continue;
    				arrayOfInt1[k] += 1;
    			}
    		}
     
    		try {
    			BufferedReader bf = new BufferedReader(new FileReader("c:\\dictionary.txt"));
    			String str3;
    			while ((str3 = bf.readLine()) != null) {
    				int m = str3.length();
    				char[] arrayOfChar3 = str3.toCharArray();
     
    				for (int n = 1; n < 27; n++) {
    					arrayOfInt2[n] = 0;
    				}
     
    				for (int n = 0; n < m; n++) {
    					for (int i1 = 1; i1 < 27; i1++) {
    						if (arrayOfChar3[n] != arrayOfChar2[i1])
    							continue;
    						arrayOfInt2[i1] += 1;
    					}
    				}
     
    				//int n = 0;
    				int i1 = 0;
     
    				for(int i2 = 1; i2 < 27; i2++) {
    					if (arrayOfInt2[i2] == arrayOfInt1[i2]) {
    						i1++;
    					}
    					if (arrayOfInt2[i2] > arrayOfInt1[i2])
    						continue;
    					//n++;
    				}
     
    				if (i1 == 26) {
     
    					System.out.print(" Maximum string found " + str3);
    				}
     
    				//if (n == 26) {
    					//System.out.print(" also " + str3);
    				//}
    			}
     
    			bf.close();
    		}
     
    		catch (IOException e) {
    			System.out.println("IO Error Occurred: " + e.toString());
     
    	}
     
    }
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Read from .txt file inside Jar

    You've got to call getResourceAsStream(...) on a valid Class or ClassLoader object.
    Tolls likes this.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Read from .txt file inside Jar

    Java Code:
    <YourClassName>.class.getResourceAsStream(<your file location in the jar relative to the class>);
    The location is relative to the class.
    If you want something from the "top" of the jar file then start with a "/".
    So "/somefolder/myfile.txt" will retrieve the file from the "somefolder" at the top of the jar file, whereas "somefolder/myfile.txt" will get it from a "somefolder" in the same place the class file is located.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    Raigeki is offline Nocturnal Beast
    Join Date
    Jan 2013
    Posts
    8
    Rep Power
    0

    Default Re: Read from .txt file inside Jar

    Thanks for helping me, guys. I kind of mixed your responses with a line of code I found online and ended up with this. I don't know if it's the most optimal way of doing it, but it works perfectly.

    Java Code:
    InputStream inp = Unscrambler.class.getClassLoader().getResourceAsStream ("unscrambler/Dictionairy.txt");
    BufferedReader bf = new BufferedReader(new InputStreamReader(inp));
    
    //The program continues with the bf variable from the BufferedReader//
    The reason why I had problems was because I had to include the BufferedReader and a variable for the InputStream to continue through the rest of the code. It works like a charm now, though. It took some time but I'd much rather spend 10 hours on my own trying to figure it out than waste 10 minutes of your time with an endless stream of stupid questions.

    Again, thank you for helping me.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Read from .txt file inside Jar

    No need at all to get the ClassLoader.
    The class version of getResourceAsStream is all you need.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    Raigeki is offline Nocturnal Beast
    Join Date
    Jan 2013
    Posts
    8
    Rep Power
    0

    Default Re: Read from .txt file inside Jar

    Okay, I'll remove it then.

    I cleaned and built the project yesterday and it ran just fine a couple of times. I then swapped the text file in the Jar with another one with the exact same name and now it doesn't work anymore. I deleted the ".getClassLoader()" later on, so the problem was not caused by that.
    It's just weird because the NetBeans IDE wasn't even open when the Jar suddenly decided not to work. I only opened the Jar with WinRar and "refreshed" the text file in it and tried to run it again. Is this a problem with the Manifest file or what is it?

    I tried to change the path of the text file to a copy of it on my C drive to see what error I get when I run it in NetBeans, and this is what it says:

    Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:60)
    at java.io.InputStreamReader.<init>(InputStreamReader .java:54)
    at unscrambler.Unscrambler.main(Unscrambler.java:41)
    Java Result: 1


    As far as I can tell, there is an error with the code itself. The error is that the "inp" variable on line 40 is null which means that:
    a: The text file could not be found or the InputStream failed.
    b: The BufferedReader tries to work with an empty variable/null and that causes the error.

    Am I correct? How do I fix this problem? inp should not be null because it used to work just fine.

    Java Code:
    package unscrambler;
    import java.io.*;
    import javax.swing.JOptionPane;
    
    public class Unscrambler {
     
     
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
                while (true) 
    { 
    		String str1 = javax.swing.JOptionPane.showInputDialog("Please type the scrambled word");
    		char[] arrayOfChar1 = str1.toCharArray();
     
    		int i = str1.length();
     
    		String str2 = "/abcdefghijklmnopqrstuvwxyz";
    		char[] arrayOfChar2 = str2.toCharArray();
     
    		int[] arrayOfInt1 = new int[27];
    		int[] arrayOfInt2 = new int[27];
     
    		for (int j = 1; j < 27; j++) {
    			arrayOfInt1[j] = 0;
    		}
     
    		for (int j = 0; j < i; j++) {
    			for (int k = 1; k < 27; k++) {
    				if (arrayOfChar1[j] != arrayOfChar2[k])
    					continue;
    				arrayOfInt1[k] += 1;
    			}
    		}
     
    		try {
                      
                            
                            InputStream inp = Unscrambler.class.getResourceAsStream ("C:\\Dictionairy.txt");
                            BufferedReader bf = new BufferedReader(new InputStreamReader(inp));  //Here is the error//
                        
    			String str3;
    			while ((str3 = bf.readLine()) != null) {
    				int m = str3.length();
    				char[] arrayOfChar3 = str3.toCharArray();
     
    				for (int n = 1; n < 27; n++) {
    					arrayOfInt2[n] = 0;
    				}
     
    				for (int n = 0; n < m; n++) {
    					for (int i1 = 1; i1 < 27; i1++) {
    						if (arrayOfChar3[n] != arrayOfChar2[i1])
    							continue;
    						arrayOfInt2[i1] += 1;
    					}
    				}
     
    				//int n = 0;
    				int i1 = 0;
     
    				for(int i2 = 1; i2 < 27; i2++) {
    					if (arrayOfInt2[i2] == arrayOfInt1[i2]) {
    						i1++;
    					}
    					if (arrayOfInt2[i2] > arrayOfInt1[i2])
    						continue;
    					//n++;
    				}
     
    				if (i1 == 26) {
     
    					JOptionPane.showMessageDialog(null, str3);
    				}
     
    				//if (n == 26) {
    					//System.out.print(" also " + str3);
    				//}
    			}
     
    			bf.close();
    		}
     
    		catch (IOException e) {
    			System.out.println("IO Error Occurred: " + e.toString());
     
    	}
     
    }
    }
    }

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Read from .txt file inside Jar

    You can't use getResourceAsStream with any old file location.
    It is purely related to the classpath Java is using for your application.

    Try again with the file in your jar.
    Post the relevant code here (basically the InputStream line) and the full stack trace, and also the exact location of the file inside the jar.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    Raigeki is offline Nocturnal Beast
    Join Date
    Jan 2013
    Posts
    8
    Rep Power
    0

    Default Re: Read from .txt file inside Jar

    I'm in school right now so I'll probably look at the code in an hour or two. I have some questions, so if you or anyone else would like to answer them, it will be easier for me to proceed.

    1. What is an "old file location"? Is it the location of a file that has been deleted or replaced?
    2. When I use getResourceAsStream(), I can -only- get files inside the Jar as resources. Is that correct?
    3. Do I have to somehow include the text file in the Jar within the NetBeans IDE or do I just put it in the Jar when it has been cleaned and built by opening it with WinRar?
    4. If I have to post the full stack trace, I have to run the file in the NetBeans IDE, right? How can I do that if I have to run the Jar by itself to test if the text file has been read correctly? Or can I run the Jar through Netbeans?

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Read from .txt file inside Jar

    1. Sorry, that's an English phrase. :)
    I meant, getResourceAsStream works only in relation to the classpath used by the application. You can't "break out" of that to read a file located elsewhere on your machine.
    2. Not too sure what you're asking here. They are resources. But a resource can mean any sort of file.
    3. If the file is in a folder (or sub folder of one) that is a source folder then Netbeans will include it in the build, and so the jar file. The easiest way to do this is simply stick the file in the src directory (or a sub directory of that one).
    4. Run the jar file from the command line and copy/paste the results.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    Raigeki is offline Nocturnal Beast
    Join Date
    Jan 2013
    Posts
    8
    Rep Power
    0

    Default Re: Read from .txt file inside Jar

    I noticed a few mistakes I've made. Very stupid mistakes.

    1: The classpath of the text file is in relation to the class as you mentioned earlier. I fixed this by removing "/" at the beginning. I don't know why I forgot to do that, but the application is now able to find the text file.

    2: I asked myself: If the InputStream suddenly returns null from a file it can find when I haven't even changed the code, something else must be wrong. The only thing I had done was to "update" the text file and it completely stopped returning anything. It turns out that there is a big difference between c and C for example, haha. Long story short, the first text file contained only lower-case letters and the words in the second text file starts with upper-case letters.
    The whole thing has worked since yesterday but I only tested with lower-case words. All the NullPointerExceptions were caused by the fact that I searched for cat instead of Cat. But hey, I had only been interested in coding for about 4 days when I created the first post. Beginner mistakes ;)

    Anyway, thank you for helping me with the getResourcAsStream-part and making me realize these mistakes.
    DarrylBurke likes this.

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Read from .txt file inside Jar

    That's good news.
    Always nice to solve your own problems as well.
    That "Eureka!" moment...:)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  12. #12
    Raigeki is offline Nocturnal Beast
    Join Date
    Jan 2013
    Posts
    8
    Rep Power
    0

    Default Re: Read from .txt file inside Jar

    Haha yeah, that is the best way to learn ;)

    Okay, so I actually have question that has something to do with the same code, so I might as well keep this thread alive.
    I don't want to waste too much space, so I'll just include the exact part I'm having problems with:

    Java Code:
    if (i1 == 26) {
     
                        JOptionPane.showMessageDialog(null, str3);
                    }
    ______________________________________________

    Optional reading:

    That is on line 72-74 in the full code I posted earlier today. I wanted to include the program in a JFrameForm to make it more appealing, so I simply copied it to a JFrameForm, changed the class names and so on. But the (null, str3) part of the code above gives me an error when I try to change it to outputtxt.setText(null, str3) to output str3 in a text field. The null or the comma is probably what causes the error and the code is error-free when I delete those, leaving outputtxt.setText(str3);. This just happened because I went from a JOptionPane to a JFrame output, right?

    ______________________________________________

    Here is where it gets weird: I honestly don't think I need the "null, " in front of the string, but that is the only thing I changed when I copied the code to the JFrame and now the program freezes when I run the code with a jButton.
    I can't see anything in the stack trace as it is completely empty because the program locks up and needs to be killed with Task Manager. And that means I don't know where the error occurs. I purposely pasted the whole code in the ActionPerformed method for the Convert button and not in main method, but I fail to see how that should make a difference. I've made other programs with the same layout and they work just fine. Is this problem linked with the fact that it says "outputtxt.setText(str3)" without the null (I doubt it) or is it just my layout and that is really bad?

    Java Code:
    package unscrambler.V2;
    import java.io.*;
    
    public class UnscramblerVisual extends javax.swing.JFrame {
    
      
        public UnscramblerVisual() {
            super("The Unscrambler");
            initComponents();
        }
    
        
            jLabel1.setText("Please type the scrambled word:");
    
            jLabel2.setText("Here you go:");
    
    
    //***************This is the button that makes the program freeze*****************//
        private void mainButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
             while (true) 
    { 
            String str1 = inputtxt.getText();
            char[] arrayOfChar1 = str1.toCharArray();
     
            int i = str1.length();
     
            String str2 = "/abcdefghijklmnopqrstuvwxyz";
            char[] arrayOfChar2 = str2.toCharArray();
     
            int[] arrayOfInt1 = new int[27];
            int[] arrayOfInt2 = new int[27];
     
            for (int j = 1; j < 27; j++) {
                arrayOfInt1[j] = 0;
            }
     
            for (int j = 0; j < i; j++) {
                for (int k = 1; k < 27; k++) {
                    if (arrayOfChar1[j] != arrayOfChar2[k])
                        continue;
                    arrayOfInt1[k] += 1;
                }
            }
     
            try {
                      
                            
                            InputStream inp = UnscramblerVisual.class.getResourceAsStream ("Dictionairy.txt");
                            BufferedReader bf = new BufferedReader(new InputStreamReader(inp));  
                        
                String str3;
                while ((str3 = bf.readLine()) != null) {
                    int m = str3.length();
                    char[] arrayOfChar3 = str3.toCharArray();
     
                    for (int n = 1; n < 27; n++) {
                        arrayOfInt2[n] = 0;
                    }
     
                    for (int n = 0; n < m; n++) {
                        for (int i1 = 1; i1 < 27; i1++) {
                            if (arrayOfChar3[n] != arrayOfChar2[i1])
                                continue;
                            arrayOfInt2[i1] += 1;
                        }
                    }
     
                    //int n = 0;
                    int i1 = 0;
     
                    for(int i2 = 1; i2 < 27; i2++) {
                        if (arrayOfInt2[i2] == arrayOfInt1[i2]) {
                            i1++;
                        }
                        if (arrayOfInt2[i2] > arrayOfInt1[i2])
                            continue;
                        //n++;
                    }
     
                    if (i1 == 26) {
                                        
     
                        outputtxt.setText(str3);
                    }
     
                    
                }
     
                bf.close();
            }
     
            catch (IOException e) {
                outputtxt.setText("IO Error Occurred: " + e.toString());
     
        }
     
    }
    
        }                                        
    
    //*****************End of button******************//
    
    
        public static void main(String args[]) {
       
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Unscrambler().setVisible(true);
                }
            });
        }
    Last edited by Raigeki; 02-01-2013 at 12:56 AM.

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Read from .txt file inside Jar

    For the first part, you need to get used to reading the API.
    JOptionPane and JTextField are different things, with different methods, which have different parameters.
    The API will explain what those parameters are.

    For the second part, your action consists of a while(true) loop.
    I assume this is the code that is run when the button is pressed.
    For this you need to learn about the EDT.
    This is the Event Dispatch Thread.
    All Swing events occur on this thread.
    This includes the event that results from clicking the button, which then calls your code above.
    That code goes into an infinite loop, all on the EDT. That means no other events can be fired until the ActionEvent has completed, which it will never do because it is an infinite loop.

    The solution (which is given in that tutorial link) is to launch another thread (using a SwingWorker) to do any long running tasks.
    Raigeki likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  14. #14
    Raigeki is offline Nocturnal Beast
    Join Date
    Jan 2013
    Posts
    8
    Rep Power
    0

    Default Re: Read from .txt file inside Jar

    Okay, so "null, " creates a default, centered frame parent for the JOptionPane. In my case, I only need the str3 string for the JTextField and therefore my problem should not be connected to that in any way.

    The while(true) loop is run when I press the button, yes. I can see why the infinite loop is a problem and it explains the "oddities" of the program perfectly. It makes sense that it freezes because it's stuck in the same loop. To sum it all up, I need to learn about the Event Dispatch Thread and launch another thread for the loop to run on to keep the program from freezing?

    I haven't really heard of threads in the tutorials I've read and watched, but I guess it's time to learn about it now. I'll take a look at the tutorial you linked and try to figure out how to fix my problem and if that doesn't work out for me, I'll come back in a day or so ;)

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Read from .txt file inside Jar

    That Swing concurrency tutorial is pretty good, and has examples that you can use as a basis for your own code.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. How to read filename inside .gz file?
    By kathir0301 in forum New To Java
    Replies: 1
    Last Post: 12-08-2010, 03:44 AM
  2. how we can read inside all of files in a directory
    By cowboy2010 in forum New To Java
    Replies: 9
    Last Post: 08-03-2010, 04:55 PM
  3. how to read the ArrayList inside HashMap
    By koddy in forum New To Java
    Replies: 6
    Last Post: 07-15-2010, 01:41 PM
  4. I can't read a text file located inside my jar.
    By Serrano0811 in forum New To Java
    Replies: 1
    Last Post: 04-21-2010, 05:03 PM
  5. Replies: 2
    Last Post: 11-29-2009, 10:26 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •