2

I've been browsing the site since yesterday and I can't see to find anything that answers my question, so I decided to just ask.

I'm making a pretty basic java GUI, it's designed to be run alongside files that wont be included in the actual java package for compatibility and easier customization of those files, I doubt they could be included either way as they have their own .jars and other things.

So, the problem I'm having is that the GUI application is in the main folder and I need it to locate and open txt files a couple sub-folders deep, in notepad without requiring a full file path as I'll be giving this project out to some people when it's done.

Currently I've been using this to open the files, but will only work for files in the main folder and trying to edit in any file paths did not work.

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    Runtime rt=Runtime.getRuntime();

    String file;
    file = "READTHIS.txt";

    try {
        Process p=rt.exec("notepad " +file);
    } catch (IOException ex) {
        Logger.getLogger(NumberAdditionUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}  

if someone knows a way to do this, that'd be great.

On another note, I'd like to include the file shown above (READTHIS.txt) inside the actual java package, where would I put the file and how should I direct java towards it?

I've been away from java for a long time so I've forgotten pretty much anything, so simpler explanations are greatly appreciated. Thanks to anyone reading this and any help would be awesome.

Yuuen
  • 45
  • 7

1 Answers1

1

Update 2

So I added to the ConfigBox.java source code and made jButton1 open home\doc\READTHIS.txt in Notepad. I created an executable jar and the execution of the jar, via java -jar Racercraft.jar, is shown in the image below. Just take the example of what I did in ConfigBox.java and apply it to NumberAdditionUI.java for each of its JButtons, making sure to change the filePath variable to the corresponding file name that you would like to open.

Note: The contents of the JTextArea in the image below were changed during testing, my code below does not change the contents of the JTextArea. Working jar...

Directory structure:

\home
    Rasercraft.jar
    \docs
        READTHIS.txt

Code:

// imports and other code left out

public class ConfigBox extends javax.swing.JFrame {
    // curDir will hold the absolute path to 'home\'
    String curDir; // add this line

    /**
     * Creates new form ConfigBox
     */
    public ConfigBox() 
    {
        // this is where curDir gets set to the absolute path of 'home/'
        curDir = new File("").getAbsolutePath(); // add this line

        initComponents();
    }

    /*
     * irrelevant code
     */

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Runtime rt = Runtime.getRuntime();

        // filePath is set to 'home\docs\READTHIS.txt'
        String filePath = curDir + "\\docs\\READTHIS.txt"; // add this line

        try {
            Process p = rt.exec("notepad " + filePath); // add filePath
        } catch (IOException ex) {
            Logger.getLogger(NumberAdditionUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    /*
     * irrelevant code
     */


Update

This is the quick and dirty approach, if you would like me to add a more elegant solution just let me know. Notice that the file names and their relative paths are hard-coded as an array of strings.

Image of the folder hierarchy:

Directory structure.

Code:
Note - This will only work on Windows.

import java.io.File;
import java.io.IOException;

public class Driver {

    public static void main(String[] args) {
        final String[] FILE_NAMES = {"\\files\\READTHIS.txt",
                                     "\\files\\sub-files\\Help.txt",
                                     "\\files\\sub-files\\Config.txt"
                                    };
        Runtime rt = Runtime.getRuntime();

        // get the absolute path of the directory
        File cwd = new File(new File("").getAbsolutePath());

        // iterate over the hard-coded file names opening each in notepad
        for(String file : FILE_NAMES) {
            try {
                Process p = rt.exec("notepad " + cwd.getAbsolutePath() + file);
            } catch (IOException ex) {
                // Logger.getLogger(NumberAdditionUI.class.getName())
                // .log(Level.SEVERE, null, ex);
            }
        }

    }
}


Alternative Approach

You could use the javax.swing.JFileChooser class to open a dialog that allows the user to select the location of the file they would like to open in Notepad.

JFileChooser dialog


I just coded this quick example using the relevant pieces from your code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class Driver extends JFrame implements ActionListener {
    JFileChooser fileChooser;  // the file chooser
    JButton openButton;  // button used to open the file chooser
    File file; // used to get the absolute path of the file

    public Driver() {
        this.fileChooser = new JFileChooser();
        this.openButton = new JButton("Open");

        this.openButton.addActionListener(this);

        // add openButton to the JFrame
        this.add(openButton);

        // pack and display the JFrame
        this.pack();
        this.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        // handle open button action.
        if (e.getSource() == openButton) {
            int returnVal = fileChooser.showOpenDialog(Driver.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                // from your code
                Runtime rt = Runtime.getRuntime();

                try {
                    File file = fileChooser.getSelectedFile();
                    String fileAbsPath = file.getAbsolutePath();

                    Process p = rt.exec("notepad " + fileAbsPath);                        
                } catch (IOException ex) {
                    // Logger.getLogger(NumberAdditionUI.class.getName())
                    // .log(Level.SEVERE, null, ex);
                }
            } else {
                System.exit(1);
            }
        }

    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Driver driver = new Driver();
            }
        });
    }

}

I've also included a link to some helpful information about the FileChooser API, provided by Oracle: How to use File Choosers. If you need any help figuring out the code just let me know, via a comment, and I'll try my best to help.

As for including READTHIS.txt inside the actual java package, take a gander at these other StackOverflow questions:

Community
  • 1
  • 1
Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
  • Thanks for the quick reply, but I think either I didn't explain correctly or I was misunderstood, but I didn't mean for them to be able to choose a file to open, I just need it to open a set file in the sub-folder, like a configuration file, help file etc. – Yuuen Sep 24 '15 at 04:19
  • I'll explain a bit more if that helps, lets say I have the main folder called "home" and in that folder I have another folder called "docs", the java application is in "home" and I want it to open a help file inside "docs" just by pressing a jbutton, however I don't want it to require a full file path like C:\Users\Freddy\Documents\home\docs\help.txt, I want it to just be able to use \home\docs\help.txt or even just \docs\help.txt so that when it's distributed it can be used anywhere as long as it's inside that "home" folder. – Yuuen Sep 24 '15 at 05:23
  • @Raserhead are you executing a `.jar` or are you using the `java` command in a command prompt or an IDE? Also if your code isn't too large could you add it in it's entirety to your question, or possibly upload your project somewhere and let me download it? – Jonny Henly Sep 24 '15 at 05:30
  • You run the java application which will open a gui, from there i've got a jbutton which opens a new jframe with other jbuttons, each of those jbuttons are going to be linked to a certain txt file, those txt files are going to be used by other things, that's why I can't just put them all into the package. If that still doesn't explain things, I can grab you the java app. – Yuuen Sep 24 '15 at 05:36
  • @Raserhead I understand what your describing and I could code up an example based off your description, but it would probably be faster and easier if I just had a look at your code. So if you could provide me with a download link that would great. – Jonny Henly Sep 24 '15 at 05:44
  • No, they will be outside of the jar. As I said before, jar will be in a main folder and the txt files it's going to open in the sub-directories of that main folder. – Yuuen Sep 24 '15 at 06:52
  • @Raserhead updated my answer and hopefully it is the solution. – Jonny Henly Sep 24 '15 at 07:32
  • I'll give it a shot, thanks for all your help. You've done way more than I thought anyone would do. – Yuuen Sep 24 '15 at 07:37
  • @Raserhead Turtally. Thank you though, I was bored and you gave me something to do. – Jonny Henly Sep 24 '15 at 07:41
  • Works perfectly! Thanks again! – Yuuen Sep 24 '15 at 07:53
  • One last question though, in the Process p=rt.exec("notepad "+file); section of the code, how would I specify a different program such as notepad++, I have tried just changing it to the notepad++, but it doesn't seem to work. So I imagine I'm required to specify what it is. – Yuuen Sep 24 '15 at 07:58
  • @Raserhead you'll either have to include the path of the `notepad++` installation directory (where `notepad++.exe` is located) in your system path, or include the absolute path of `notepad++.exe` in the `Process p=rt.exec("notepad "+file);` line. For instance `Process p=rt.exec("C:\\Path\\to\\notepad++.exe "+file);`. More info can be found [here](http://docs.notepad-plus-plus.org/index.php/Command_Line_Switches). – Jonny Henly Sep 24 '15 at 08:04
  • Alright. As far as I know, notepad++ installation is pretty uniform, so hopefully I can get away with a set file path, from memory it's C:\\Program Files (x86)\\Notepad++\\Notepad++.exe. Thanks again for all your help. – Yuuen Sep 24 '15 at 08:07
  • @Raserhead yep no problem, let me know if you need anything else. – Jonny Henly Sep 24 '15 at 08:08