DSlomer64
DSlomer64

Reputation: 4283

How do I open a Netbeans empty file in Java/

Here's my Netbeans project structure:

enter image description here

Maine is the class with main. I want to read the lines of text in the Netbeans "empty file" HighlightInput with a Scanner object, but I can't figure out how to do so.

Because of what works for a different project (see below), I tried this (and a lot of other things):

    InputStream myStream = null;

    myStream =  Class.forName("gbl/Maine").getClassLoader() //// exception here
                     .getResourceAsStream("HighlightInput");
  Path p = Paths.get(myStream.toString());
  Scanner sc = new Scanner(p);

Exception in thread "AWT-EventQueue-0" java.security.PrivilegedActionException: java.lang.ClassNotFoundException: gbl/Maine

Because of something else that also works below, I tried this:

  File file = new File("src/HighlightInput");      
  Scanner sc = new Scanner(file);          //// exception here

Exception in thread "AWT-EventQueue-0" java.security.PrivilegedActionException: java.io.FileNotFoundException: src\HighlightInput (The system cannot find the path specified)

What should I do to read the file "HighlightInput"?

=========================

Here's why I tried what I did--I followed two different apparent patterns, unsuccessfully:

Here's what works for a different project (Masterwords contains main), structure listed below, to read Netbeans file named "Help":

  myStream =  Class.forName("masterwords.Masterwords").getClassLoader()
      .getResourceAsStream("Help"); 

enter image description here

The following works to read the file named "dictionary":

File file = new File("src/dictionary");
Path in_path = file.toPath();

Upvotes: 0

Views: 1003

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

    InputStream myStream = Maine.class.getResourceAsStream("/HighlightInput");
    Scanner sc = new Scanner(myStream, "UTF-8");

Resources are no File, but may reside in a .jar. In the same jar/same classes dir, you may use something like getClass().getResource(...). This is relative to the classes package directory, hence the "/Highlight" which corresponds to the root dir aka default package.

The scanner may immediate work on that InputStream. It is needed to indicate the character set encoding, as otherwise the local operating system encoding is taken - unportable.

If you want to write to the resource file: don't - because of the normal case of compiling to a .jar as distributed application. Use the resource in that case as a template and copy it to some directory in the user's home directory.

Upvotes: 2

Related Questions