无法设置文件的正确路径

时间:2019-03-28 00:05:23

标签: java

我尝试了几种使用Path来实现到文件正确路径的方法,但是到目前为止,我还没有成功。我正在尝试写入/重写文件。

在代码片段中,我将显示到目前为止我已经尝试过的内容,但是我似乎找不到正确的方法。这也是我的包裹的层次结构示例

src
├── information
│   └── destination
│       └── (empty)
└── classpackage
    └── MyClass.java

我正在尝试保持相对于项目本身的路径,以便任何人都可以对其进行编译,并且可以在项目包层次结构中的正确位置创建文件,无论他们将src文件夹放在何处。 / p>

这是在MyClass.java内部

private static final File FILE = new File("/src/information/destination", "data.set");

ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE.getAbsolutePath())); //doesn't work

ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE)); //doesn't work

ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE.getAbsoluteFile())); //doesn't work

2 个答案:

答案 0 :(得分:0)

您需要获取绝对路径,并使用该绝对路径引用所需的文件。 Java提供了FileSystem的帮助。获取绝对路径后,添加文件的文件路径。

import java.io.ObjectInputStream;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.FileSystems;

class FileRead {
  public static void main(String[] args) {
    try {
        String filePath =
        FileSystems.getDefault().getPath(".").
        toAbsolutePath()+"/Practice/Stack";
        File file = new File(filePath,"test.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String st; 
        while ((st = br.readLine()) != null) {
            System.out.println(st); 
        }
    } catch (Exception e) {
        // TODO: handle exception
        System.out.println(e.getMessage());
    }finally{}
  }
}

答案 1 :(得分:0)

只需更改路径即可。 src / information / destination

以及

之类的文件路径

enter image description here 解决方案:

package classpackge;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class MyClass {
    private static final File FILE = new File("src/information/destination", "data.set");

    public static void main(String[] args) throws FileNotFoundException, IOException {
        FileInputStream in =new FileInputStream(FILE.getAbsolutePath()); //doesn't work
in.close();
        //ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE)); //doesn't work

        //ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE.getAbsoluteFile())); //doesn't work
    }
}