Nav
Nav

Reputation: 71

input from file in java

I am java beginner learner and i am trying to output the data on file which i call a.txt. need help i have no idea y i am getting exception error file not open . i put a.txt in the same directory in which i have main and readfile.

- main path : C:\Users\Navdeep\Desktop\java\assign1\src\assign1

- readfile : C:\Users\Navdeep\Desktop\java\assign1\src\assign1

- a.txt :  C:\Users\Navdeep\Desktop\java\assign1\src\assign1

Thanks in advance .

main.java

package assign1;

public class main {
    public static void main(String[] args) {
        readfile r = new readfile();
        r.openFile();
        r.readFile();
        r.closeFile();
    }
}

readile.java

package assign1;

import java.io.*;
import java.util.*;

public class readfile {
    private Scanner x;

    public void openFile() {
        try {
            x = new Scanner(new File("a.txt"));
        } catch (Exception e) {
            System.out.println("file not open \n");
        }
    }

    public void readFile() {
        while (x.hasNext()) {
            String Agent = x.next();
            String request_type = x.next();
            String classtype = x.next();
            String numberofseat = x.next();
            String arrivaltime = x.next();

            System.out.printf("%s %s %s %s %s \n", Agent, 
                    request_type, classtype, numberofseat, arrivaltime);
        }
    }
    public void closeFile() {
        x.close();
    }
}

a.txt

1 r e 1 0
2 r e 1 1 

Upvotes: 1

Views: 273

Answers (3)

Zuko
Zuko

Reputation: 2914

Here is one using BufferedReader.

    public static void main(String[] args) {
        // check for arguments. this expects only one argument @index [0]
        if (args.length < 1) {
            System.out.println("Please Specify your file");
            System.exit(0);
        }
        // Found atleast one argument
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        // Prefer using a buffered reader depending on size of your file
        try {
            reader = new FileReader(new File(args[0]));
            bufferedReader = new BufferedReader(reader);
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null)
               content.append(line);
            System.out.println(content.toString());
        } catch (IOException e) {
        e.printStackTrace();
        } finally {
        // dont forget to close your streams
            try {
                if (bufferedReader != null)
                   bufferedReader.close();
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
            e.printStackTrace();
         }
       }
    }

Let me know if you have any isues.

Good_luck_programming!

Upvotes: 0

augray
augray

Reputation: 3161

If you use a File with a relative path, it is assumed relative to the "current user directory". What's the "current user directory"? See the doc:

A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

Also from the doc:

On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.

So one way to get the File to be found using a relative path would be to start the JVM in the directory with the file.

However, this approach can be kind of limiting since it constrains you to always start the JVM in a certain directory.

As an alternative, you might consider using ClassLoader#getResourceAsStream. This allows you to load any resource that is on the JVM's "classpath". The classpath can be configured in a number of different ways, including at launch time using arguments to the JVM. So I would suggest using that, rather than initializing your Scanner with a File. This would look like:

InputStream is = StackOverflow.class.getClassLoader().getResourceAsStream("a.txt");
Scanner scanner = new Scanner(is);

Now, when using getResourceAsStream, you have to make sure that the file referenced is on the classpath of the Java Virtual Machine process which holds your program.

You've said in comments that you're using Eclipse.

In Eclipse, you can set the classpath for an execution by doing the following:

1) After running the program at least once, click on the little dropdown arrow next to the bug or the play sign.

2) Click on "Debug configurations" or "Run Configurations".

3) In the left sidebar, select the run configuration named after the program you're running

4) Click on the "Classpath" tab

5) Click on "User Entries"

6) Click on "Advanced"

7) Select "Add Folders"

8) Select the folder where a.txt resides.

Once you have done this, you can run the program using the run configuration you have just set up, and a.txt will be found.

Basic idea of classpath

The classpath represents the resources that the JVM (Java Virtual Machine) holding your program knows about while it's running. If you are familiar with working from a command line, you can think of it as analogous to your OS's "PATH" environment variable.

You can read about it in depth here.

Upvotes: 2

Nav
Nav

Reputation: 71

Instead of putting the file in src folder put the txt file in the project ie outside the src.

Upvotes: 0

Related Questions