0

So I have the following code that takes the users input as a String which is the name of a file and inputs it into a Scanner object.

        System.out.print("What is the name of the input file?");
        String name = scan.nextLine();
        Scanner file = new Scanner(new File(name));

What is the proper location to place a file so that it can be accessed. Would I have to keep the file in the same folder as this project or is it possible to have them in different folders and still be able to reference it. I am using a mac if that helps.

Mathew Jacob
  • 35
  • 1
  • 5
  • [Debug using this](https://stackoverflow.com/questions/4871051/getting-the-current-working-directory-in-java) and you'll get your answer – Turtle May 23 '17 at 13:45
  • Maybe I misunderstood your question, sorry. You can access files outside of your current directory if that was your question. – Turtle May 23 '17 at 13:46

2 Answers2

0

Would I have to keep the file in the same folder as this project or is it possible to have them in different folders and still be able to reference it.

You can keep it anywhere in your machine(provided you have valid read permission on the directory you are trying to access).

Scanner file = new Scanner(new File(name));

This will work when your file is in the current directory, else you have to give the complete path.

Update: How to give Complete Path :

import java.util.*;
import java.io.*;
public class TestFile
{
    public static void main(String str[]) throws Exception
    {
        try
        {
            System.out.print("What is the name of the input file?");
            Scanner scan = new Scanner(System.in);
            String name = scan.nextLine();
            File file = new File("/Users/jaine03/Desktop/"+name);
            System.out.println(file.exists());
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }
}

Output

What is the name of the input file?
TestFile.java
true
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

It is important to differentiate between relative and absolute paths.

You could put it under your CLASSPATH, for example in a directory "resources".

Or you could use an absolute path and reference every accessible file.

  • windows: new File("c:\\path\\file.dat")
  • linux / mac: new File("/path/file.dat")

But its better to use meta descriptions or APIs, like java.nio.file.Paths, in order to get information about the current working directory, which will make the application more portable and robust.

The following example gets the applications current directory path as a String:

Paths.get(".").toAbsolutePath().normalize().toString();

Also see API in java.nio.file.Path (e.g. https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html):

  • Path relativize(Path other)
  • Path resolve(Path other)
  • Path resolveSibling(Path other)
  • Path toAbsolutePath()
  • ...
ratech
  • 11
  • 5