How do relative file paths work in Eclipse?

前端 未结 6 1239
后悔当初
后悔当初 2020-11-29 01:10

So my 2009 new years resolution is to learn Java. I recently acquired \"Java for Dummies\" and have been following along with the demo code in the book by re-writing it usi

相关标签:
6条回答
  • 2020-11-29 01:31

    You can always get your runtime path by using:

     String path = new File(".").getCanonicalPath();
    

    This provides valuable information about where to put files and resources.

    0 讨论(0)
  • 2020-11-29 01:39

    You need "src/Hankees.txt"

    Your file is in the source folder which is not counted as the working directory.\

    Or you can move the file up to the root directory of your project and just use "Hankees.txt"

    0 讨论(0)
  • 2020-11-29 01:47

    A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

    New run configurations default to using the project directory for the working directory, though this can also be changed.

    This code shows the difference between the working directory, and the location of where the class was loaded from:

    public class TellMeMyWorkingDirectory {
        public static void main(String[] args) {
            System.out.println(new java.io.File("").getAbsolutePath());
            System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
        }
    }
    

    The output is likely to be something like:

    C:\your\project\directory
    /C:/your/project/directory/bin/
    
    0 讨论(0)
  • 2020-11-29 01:48

    Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.

    ...just thought I'd add some extra info. I'm new here! I'd like to help.

    0 讨论(0)
  • 2020-11-29 01:49

    This is really similar to another question. How should I load files into my Java application?

    How should I load my files into my Java Application?

    You do not want to load your files in by:

    C:\your\project\file.txt
    

    this is bad!

    You should use getResourceAsStream.

    InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);
    

    And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.

    0 讨论(0)
  • 2020-11-29 01:52

    Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:

    The classes under java.io resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.

    Eclipse sets the working directory to the top-level project folder.

    0 讨论(0)
提交回复
热议问题