Java coding question. Just learning. Fairly Simple.

I’ve decided to teach myself Java, for no reason other then for the heck of it, and because its free. For this, I’m using the online Java Tutorial. Also because its free. Everything has been going ok, up until "I/O - how to use file streams. "

Specifically, I’m right here. Trying to run this code:



import java.io.*;

public class Copy {
    public static void main(String[] args) throws IOException {
	File inputFile = new File("farrago.txt");
	File outputFile = new File("outagain.txt");

        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        int c;

        while ((c = in.read()) != -1)
           out.write(c);

        in.close();
        out.close();
    }
}


So, my understanding is I have to make a file, farrago.txt. Then, I execute this program, it makes a copy of the file and names the copy outagain.txt, then closes.

Instead, I execute it, it can’t seem to find the file farrago.txt, and errors out. java.io.FileNotFound Exception : farrago.txt. It seems pretty obvious to me I need to somehow specify the path where this file exists, except the JavaTutorial doesnt seem to mention how to go about doing that. Anyone know how to get this program to work right?

How do you run this program?
From the command line, from some IDE or an editor?

Java interprets file names as relative to your current “working directory” in the shell of both Windows and Unix this is what one expects (although the language doesn’t really guarantee that.) It is not neccessarily the directory where the class file is located.
If you use Java in an IDE, the actual directory depends on the program. e.g. NetBeans sets it to an obscure folder in your home directory, but you can change that.

Look at the javadocs for the File constructor, it sounds like you’re going to have to specify the path.

Hurray!!!

Yeah. I’m using NetBeans. I was originally testing code by simply compiling and executing ( hitting F9 then F6). I followed your advice, and moved the Copy.class and the Farrago.txt files into the same folder where the java compiler is, ran it through DOS, and it worked.

Any idea how I can set up NetBeans so it knows where to look for the files?

Any idea how to

Oops, ignore that last “any idea how to” typo in the previous post.

Goto:

menu category “Tools”
menu item “Options”
folder “Debugging and Executing”
subfolder “Execution Types”
subfolder “External Execution”

…and set the property “Working Directory” using the “…” button.

Keep in mind that this change is per project.

Thanks! All working properly now. :slight_smile: