如何从Java项目的相对路径中读取文件?. io .文件无法找到指定的路径

时间:2023-02-05 17:52:16

I have a project with 2 packages:

我有一个项目有两个包:

  1. tkorg.idrs.core.searchengines
  2. tkorg.idrs.core.searchengines
  3. tkorg.idrs.core.searchengines
  4. tkorg.idrs.core.searchengines

In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:

在包(2)中,我有一个文本文件ListStopWords。在package(1)中有一个类FileLoadder。以下是FileLoader的代码:

File file = new File("properties\\files\\ListStopWords.txt");

But have this error:

但这个错误:

The system cannot find the path specified

Can you give a solution to fix it? Thanks.

你能给我一个解决办法吗?谢谢。

9 个解决方案

#1


125  

If it's already in the classpath, then just obtain it from the classpath. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.

如果它已经在类路径中,那么只需从类路径中获取它。不要修改java.io.File中的相对路径。它们依赖于您在Java代码中完全无法控制的当前工作目录。

Assuming that ListStopWords.txt is in the same package as FileLoader class:

假设ListStopWords。txt与FileLoader类在同一个包中:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());

Or if all you're after is an InputStream of it:

或者如果你想要的只是一个输入流:

InputStream input = getClass().getResourceAsStream("ListStopWords.txt");

If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed it immediately to the load() method.

如果这个文件——正如包名提示的那样——实际上是一个完整的属性文件(包含key=value lines),只有“错误”的扩展名,那么您可以立即将它提供给load()方法。

Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));

Note: when you're trying to access it from inside static context, then use FileLoader.class instead of getClass() in above examples.

注意:当您试图从静态上下文中访问它时,请使用FileLoader。在上面的示例中,类而不是getClass()。

#2


28  

The following line can be used if we want to specify the relative path of the file.

如果我们想要指定文件的相对路径,可以使用下面的行。

File file = new File("./properties/files/ListStopWords.txt");  

#3


11  

The relative path works in in java using the . operator.

相对路径在java中使用。操作符。

  • . means same folder as the currently running context.
  • 。表示与当前运行的上下文相同的文件夹。
  • .. means the parent folder of the currently running context.
  • . .表示当前运行上下文的父文件夹。

So the question is how do you know the path where the java is currently looking?

所以问题是,你如何知道java当前查找的路径?

do a small experiment

做一个小实验

   File directory = new File("./");
   System.out.println(directory.getAbsolutePath());

Observe the output , you will come to know the current directory where java is looking . From there , simply use the ./ operator to locate your file.

观察输出,您将了解java正在查找的当前目录。从那里,只需使用./操作符来定位文件。

for example if the output is

例如,如果输出是

G:\JAVA8Ws\MyProject\content.

旅客:\ JAVA8Ws \ MyProject \内容。

and your file is present in the folder MyProject simply use

您的文件存在于MyProject简单使用的文件夹中。

File resourceFile = new File("../myFile.txt");

Hope this helps

希望这有助于

#4


4  

    InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
    try {
        BufferedReader reader=new BufferedReader(new InputStreamReader(in));
        String line=null;
            while((line=reader.readLine())!=null){
                System.out.println(line);
            }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

#5


3  

try .\properties\files\ListStopWords.txt

试一试。\ \文件\ ListStopWords.txt属性

#6


2  

While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:

虽然BalusC提供的答案适用于这种情况,但是当文件路径包含空格时,它就会中断,因为在URL中,这些空格被转换为不是有效文件名的%20。如果您使用URI而不是字符串来构造文件对象,那么将正确地处理whitespaces:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());

#7


0  

I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :

我想要解析“命令”。json的src /主/ / js / Simulator.java内部。为此,我在src文件夹中复制了json文件,并给出了如下的绝对路径:

Object obj  = parser.parse(new FileReader("./src/command.json"));

#8


-1  

If you are trying to call getClass() from Static method or static block the you can do the following way.

如果您试图从静态方法或静态块调用getClass(),您可以按照以下方式进行。

You can call getClass() on the Properties object you are loading into.

您可以在正在加载的属性对象上调用getClass()。

public static Properties pathProperties = null;

static { 
    pathProperties = new Properties();
    String pathPropertiesFile = "/file.xml;
    InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

#9


-1  

If text file is not being read, try using a more closer absolute path (if you wish you could use complete absolute path,) like this:

如果没有读取文本文件,请尝试使用更接近的绝对路径(如果您希望可以使用完整的绝对路径),如下所示:

FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");

assume that the absolute path is:

假设绝对路径为:

C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt

#1


125  

If it's already in the classpath, then just obtain it from the classpath. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.

如果它已经在类路径中,那么只需从类路径中获取它。不要修改java.io.File中的相对路径。它们依赖于您在Java代码中完全无法控制的当前工作目录。

Assuming that ListStopWords.txt is in the same package as FileLoader class:

假设ListStopWords。txt与FileLoader类在同一个包中:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());

Or if all you're after is an InputStream of it:

或者如果你想要的只是一个输入流:

InputStream input = getClass().getResourceAsStream("ListStopWords.txt");

If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed it immediately to the load() method.

如果这个文件——正如包名提示的那样——实际上是一个完整的属性文件(包含key=value lines),只有“错误”的扩展名,那么您可以立即将它提供给load()方法。

Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));

Note: when you're trying to access it from inside static context, then use FileLoader.class instead of getClass() in above examples.

注意:当您试图从静态上下文中访问它时,请使用FileLoader。在上面的示例中,类而不是getClass()。

#2


28  

The following line can be used if we want to specify the relative path of the file.

如果我们想要指定文件的相对路径,可以使用下面的行。

File file = new File("./properties/files/ListStopWords.txt");  

#3


11  

The relative path works in in java using the . operator.

相对路径在java中使用。操作符。

  • . means same folder as the currently running context.
  • 。表示与当前运行的上下文相同的文件夹。
  • .. means the parent folder of the currently running context.
  • . .表示当前运行上下文的父文件夹。

So the question is how do you know the path where the java is currently looking?

所以问题是,你如何知道java当前查找的路径?

do a small experiment

做一个小实验

   File directory = new File("./");
   System.out.println(directory.getAbsolutePath());

Observe the output , you will come to know the current directory where java is looking . From there , simply use the ./ operator to locate your file.

观察输出,您将了解java正在查找的当前目录。从那里,只需使用./操作符来定位文件。

for example if the output is

例如,如果输出是

G:\JAVA8Ws\MyProject\content.

旅客:\ JAVA8Ws \ MyProject \内容。

and your file is present in the folder MyProject simply use

您的文件存在于MyProject简单使用的文件夹中。

File resourceFile = new File("../myFile.txt");

Hope this helps

希望这有助于

#4


4  

    InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
    try {
        BufferedReader reader=new BufferedReader(new InputStreamReader(in));
        String line=null;
            while((line=reader.readLine())!=null){
                System.out.println(line);
            }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

#5


3  

try .\properties\files\ListStopWords.txt

试一试。\ \文件\ ListStopWords.txt属性

#6


2  

While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:

虽然BalusC提供的答案适用于这种情况,但是当文件路径包含空格时,它就会中断,因为在URL中,这些空格被转换为不是有效文件名的%20。如果您使用URI而不是字符串来构造文件对象,那么将正确地处理whitespaces:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());

#7


0  

I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :

我想要解析“命令”。json的src /主/ / js / Simulator.java内部。为此,我在src文件夹中复制了json文件,并给出了如下的绝对路径:

Object obj  = parser.parse(new FileReader("./src/command.json"));

#8


-1  

If you are trying to call getClass() from Static method or static block the you can do the following way.

如果您试图从静态方法或静态块调用getClass(),您可以按照以下方式进行。

You can call getClass() on the Properties object you are loading into.

您可以在正在加载的属性对象上调用getClass()。

public static Properties pathProperties = null;

static { 
    pathProperties = new Properties();
    String pathPropertiesFile = "/file.xml;
    InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

#9


-1  

If text file is not being read, try using a more closer absolute path (if you wish you could use complete absolute path,) like this:

如果没有读取文本文件,请尝试使用更接近的绝对路径(如果您希望可以使用完整的绝对路径),如下所示:

FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");

assume that the absolute path is:

假设绝对路径为:

C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt