Hello All,

Is there any way to add a text file while creating an executable jar file in eclipse?


Regards

Yes. In your "main package" you can add a folder called resources. In that resources folder you can put your files. Then you can export the project as a Runnable Jar File in eclipse by going to File->Export->(Choose Java Option)->Runnable Jar File. Here is a code sample to get you started. Keep in mind that the way I told you to add the folder and the location of that folder are *not* the only way to do it, but it is one way. You can experiment on your own to see other ways or you can read this article on accessing resources and this article on the various ways you can arrange resources in your jar files (go down to the section on loading images using getResource). Keep in mind that the code sample I provided below uses a file called test2.txt which is in a folder called resources. And if you run this on a long text file you'll be in for a surprise because JOptionPanes will probably keep popping up because of the while loop at the end.

import java.io.InputStream;
import java.util.Scanner;

import javax.swing.JOptionPane;


public class ResourceTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		InputStream stream = ResourceTest.class.getResourceAsStream("/resources/test2.txt");
		if (stream == null) JOptionPane.showMessageDialog(null, "Resource not located.");

		Scanner input = null;
		try {
		 input = new Scanner (stream);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "Scanner error");
		}
		
		while (input.hasNextLine()) JOptionPane.showMessageDialog(null, input.nextLine());
	}
	
}

Another note: I actually had to play around a lot to get all of this to work. It took me maybe 30 minutes. I wasn't able to use getResource() to read a text file at all. If anyone else has any examples of using getResource (rather than getResourceAsStream which I ended up using), that would be helpful. It doesn't really matter what you use as long as it works, but I'm just curious how it would be done. The first link I posted in my first post in this thread claims that using getResourceAsStream is much easier, which is why I switched to that (besides, I could create a Scanner from it directly, given the fact that it returns an InputStream).

Thanks for the reply.I figured out that as long as I keep the text file in the same directory as my executable jar I need not add it to the jar file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.