Sara
Sara

Reputation: 37

open a file in netbeans

I use this method in opening files, but when i opened my project it won't run because its from a mac device. where do i store the txt file and what should i write instead of

(new File("D:\\description.txt"));

the method

 Scanner inStream = null;
    try {
  inStream = new Scanner(new File("D:\\description.txt"));
}
catch (FileNotFoundException e) {
System.out.println("Erorr openenig the file");
}

while (inStream.hasNextLine ()) {
    String line = inStream.nextLine();
    System.out.println(line);
}

Upvotes: 0

Views: 979

Answers (1)

YoYo
YoYo

Reputation: 9405

A couple of approaches you can use individually, or combine:

Hard-Coding elements that should be probably left configurable. Making the path configurable, means you can have something different depending on the platform you are on.

If the file is something that belongs with the distribution, make sure it is stored at the Class Path, and access it using YourClass.class.getResourceAsStream("/description.txt"); where YourClass is a class in your distribution. resource is a path relative to the location of the class (YourClass), so if you want it at the root of the Class Path, you will need to prefix with a forward slash "/". Here, you do not need to worry about OS conventions (forward vs backward slash). As remarked by someone else, you probably should not consider your file writable in that case.

Another typical approach, for storing things that are configuration, but specific to one user, is to store it at a default path location that get's automatically resolved. A good example is the Java System Property "user.home". In the case of a windows environment, it would resolve to the %HOME% environment variable (something like /User/myuserid).

Upvotes: 1

Related Questions