0
public class RedCompiler {

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException {
        System.setIn(new FileInputStream("help.txt"));
        Lexer lexer = new Lexer();
        Parser parser = new Parser(lexer);
        parser.start();
    }

After running the above code I get the following error.
NOTE: The error message in English is:

file can´t be found and read

I hope you can help me.

Exception in thread "main" java.io.FileNotFoundException: help.txt (El sistema no puede encontrar el archivo especificado)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at redcompiler.RedCompiler.main(RedCompiler.java:26)
C:\Users\itzel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
Abra
  • 19,142
  • 7
  • 29
  • 41
Naría
  • 11
  • Netbeans has nothing to do with it. It is *your application* that can't find the file. Nothing to do with [tag:compiler-errors] or [tag:compiler-construction] either. Just basic Java I/O. – user207421 Dec 06 '19 at 04:12
  • 1
    Your code is looking for file `help.txt` in the working directory. The working directory is the value returned by `System.getProperty("user.dir")`. It appears that file `help.txt` is not located in that directory. So either move the file or add the file path in your code. – Abra Dec 06 '19 at 06:00
  • @skomisa You can't have it both ways. The issue is opening a file, not a resource. No solution involving resources is valid. – user207421 Dec 06 '19 at 06:43
  • @Naria Where is the file "help.txt" actually located? – skomisa Dec 06 '19 at 06:50

1 Answers1

-1

You don't state where you have placed the help.txt file within your project, nor how the project was run (command line vs. within NetBeans), so it is not possible to precisely diagnose your problem. But it is still possible to propose a solution.

First, do not perform the processing in main() since you will not be able to invoke the non-static method getClass() which is needed to get runtime details about your application.

Second, to simply get the code to work when running your project within NetBeans, you could place help.txt directly under the root of your project, and it would be found. But if you then tried to run the project's jar file from the command line you would get a FileNotFoundException because help.txt would not have been included in the jar file.

So instead, create a resources folder for the help.txt file directly under your existing package under the src folder. For example, if your project had a package named redcompiler under src then part of your project structure would look like this:

src
    redcompiler
        RedCompiler.java
        resources
            help.txt

This ensures that help.txt will be included in your jar file. Then, in your main() method, you can write code that will successfully access help.txt when you run within NetBeans, and also when running your project's jar file from the command line. However, while there are multiple approaches to do that, using a FileInputStream, as shown in the OP is not one of them. See the accepted answer to How can I access a txt file in a jar with FileInputStream? for more details.

Instead, you could read help.txt using a BufferedReader, which you could instantiate using an InputStream obtained by ClassLoader.getResourceAsStream() or Class.getResource(). Here is sample code that uses both approaches to read help.txt:

package redcompiler;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class RedCompiler {

    public static void main(String[] args) throws IOException, URISyntaxException {
        new RedCompiler().demo();
    }

    void demo() throws IOException, URISyntaxException {

        // Read file using ClassLoader.getResourceAsStream()
        String path = "redcompiler/resources/help.txt";
        InputStream in = getClass().getClassLoader().getResourceAsStream(path);
        System.out.println("Using ClassLoader.getResourceAsStream(): path=" + path + ", InputStream=" + in);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        System.out.println("Using ClassLoader.getResourceAsStream(): " + reader.readLine() + '\n');

        // Read file using Class.getResource()
        path = "resources/help.txt";
        URL url = getClass().getResource(path);
        System.out.println("Using Class.getResource(): path=" + path + ", URL=" + url);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        System.out.println("Using Class.getResource(): " + reader.readLine());
    }

}

This is the output when running the project within NetBeans:

run:
Using ClassLoader.getResourceAsStream(): path=redcompiler/resources/help.txt, InputStream=java.io.BufferedInputStream@15db9742
Using ClassLoader.getResourceAsStream(): This is the content of file help.txt.

Using Class.getResource(): path=resources/help.txt, URL=file:/D:/NB112/RedCompiler/build/classes/redcompiler/resources/help.txt
Using Class.getResource(): This is the content of file help.txt.
BUILD SUCCESSFUL (total time: 0 seconds)

And this is the output when running the project's jar file from the command line:

Microsoft Windows [Version 10.0.18363.476]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\johndoe>C:\Java\jdk1.8.0_221/bin/java -jar "D:\NB112\RedCompiler\dist\RedCompiler.jar"
Using ClassLoader.getResourceAsStream(): path=redcompiler/resources/help.txt, InputStream=sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream@55f96302
Using ClassLoader.getResourceAsStream(): This is the content of file help.txt.

Using Class.getResource(): path=resources/help.txt, URL=jar:file:/D:/NB112/RedCompiler/dist/RedCompiler.jar!/redcompiler/resources/help.txt
Using Class.getResource(): This is the content of file help.txt.

C:\Users\johndoe>

Notes:

  • I created the project in NetBeans using File > New Project... > Java with Ant > Java Application.
  • The java call to be made from the command line is logged in the Output window when you build your project.
  • This is the structure of the project, as shown in the Files panel in NetBeans: projectStructure
skomisa
  • 16,436
  • 7
  • 61
  • 102
  • @user207421 The OP is showing a runtime error (`FileNotFoundException`) for the statement `System.setIn(new FileInputStream("help.txt"))` and has explicitly stated _"The file can´t be found and read"_. Their problem is simply reading the text file **help.txt** using a FileInputStream in `main()`. It's absolutely nothing to do with _"It's source code in whatever his language is"_. I think you have completely misunderstood the issue. – skomisa Dec 06 '19 at 04:41
  • You made exactly that claim in your third paragraph, and you have not addressed the point about this being a compiler compiling source files which is all clearly stated in the question. IN fact your third paragraph makes no sense whatsoever. `new FileInputStream()` doesn't look inside JAR files. – user207421 Dec 06 '19 at 05:50
  • _you will not be able to invoke the non-static method `getClass()`_ Method `getClass()` is not the only way to obtain the relevant `Class` instance. – Abra Dec 06 '19 at 06:04