What I'm trying to do is save a text file (which will not change) inside the program JAR so that it can be read. The purpose of the text file is that it will be read by one of my classes, and the contents of the text file will be added to JEditorPane . The file will be basically a tutorial, and when the user clicks on the button to read the tutorial, the contents of the file will be read and displayed in a new window that appears.
I have a part of its GUI, but as far as I can store the file in the JAR, it can be accessed, I'm lost. I read that using InputStream will work, but after trying a few things, I haven't got it to work yet.
I also store images in JARs that will be used as icons for GUI windows. This is achieved by:
private Image icon = new ImageIcon(getClass() .getResource("resources/cricket.jpg")).getImage();
But this does not work when trying to get the file:
private File file = new File(getClass.getResource("resources/howto.txt"));
Here is my class as of now:
public class HowToScreen extends JFrame{ private static final long serialVersionUID = -3760362453964229085L; private JEditorPane howtoScreen = new JEditorPane("text/html", ""); private Image icon = new ImageIcon(getClass().getResource("resources/cricket.jpg")).getImage(); private BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/howto.txt"))); public HowToScreen(){ setSize(400,300); setLocation(500,200); setTitle("Daily Text Tutorial"); setIconImage(icon); howtoScreen.setEditable(false); howtoScreen.setText(importFileStream()); add(howtoScreen); setVisible(true); } public String importFile(){ String text = ""; File file = new File("howto.txt"); Scanner in = null; try { in = new Scanner(file); } catch (FileNotFoundException e) { e.printStackTrace(); } while(in.hasNext()){ text += in.nextLine(); } in.close(); return text; } public String importFileStream(){ String text = ""; Scanner in = new Scanner(txtReader); while(in.hasNext()){ text += in.nextLine(); } in.close(); return text; } }
Ignore the importFile method, because it is deleted in favor of storing the training file inside the JAR, which makes the program completely autonomous, since I am limited by the amount of space that the program can use.
EDIT: After trying all the suggestions below, I checked to see if my JAR had packed the text file, and it is not. When I open the JAR with 7zip in the folder of my resources, the image that I use for icons is, but not a text file.