在Java中访问文件路径的正确方法是什么?

时间:2016-12-09 13:41:47

标签: java

我尝试写入文件时收到FileNotFoundException,但我使用的其他类可以读取同一路径中的文件。下面是一个示例,我可以从我的资源中读取文件:

newMap = false;
    int numTilesAcross;
    BufferedImage tileset;
    String testMapPath = "/Resources/Maps/testmap.map";
    String testTileSetPath = "/Resources/Tilesets/testtileset.gif";
    String itemsPath = "/Resources/Sprites/items.gif";
    //Uses specified file as input, then transforms file contents into a 2D array "map"
    try {

        InputStream in = getClass().getResourceAsStream(testMapPath);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        numCols = Integer.parseInt(br.readLine());
        numRows = Integer.parseInt(br.readLine());
        map = new int[numRows][numCols];
        width = numCols * tileSize;
        height = numRows * tileSize;

        String delims = "\\s+";
        for (int row = 0; row < numRows; row++) {
            String line = br.readLine();
            String[] tokens = line.split(delims);
            for (int col = 0; col < numCols; col++) {
                map[row][col] = Integer.parseInt(tokens[col]);
                //System.out.println(map[row][col]);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

但是,在我项目的另一部分中,我尝试写入另一个文件(同样适用的是我尝试写入我之前使用过的文件)无法找到文件路径,如下所示:

public void saveItemLocations(){
    String itemLocationPath = "/Resources/Items/itemLocations.txt";

    try (BufferedWriter bw = new BufferedWriter(new FileWriter(itemLocationPath))){
        bw.write("test");
   } catch (IOException e) {
        e.printStackTrace();
    }
}

这是我项目的文件结构: This is the file structure for my project

2 个答案:

答案 0 :(得分:1)

您的pt可以通过以下方式解决:

FileNotFoundException

但请注意,public void saveItemLocations(){ String itemLocationPath = "/Resources/Items/itemLocations.txt"; File dir = new File("/Resources/Items"); dir.mkdirs(); // guarantees the directory hierarchy will be created if needed. try (BufferedWriter bw = new BufferedWriter(new FileWriter(itemLocationPath))){ bw.write("test"); } catch (IOException e) { e.printStackTrace(); } } 位于文件系统上,而不是/Resources/Items/itemLocations.txt

请记住,文件系统上的“资源”和“文件”之间存在很大差异。资源通常包含在Resourcejarwar文件中。它们作为资源可读,但绝对不可写。而文件系统中的文件可以是可读写的。 出现您正在尝试写入资源

Oracle的technote可以帮助您更好地理解文件和资源之间的区别。

答案 1 :(得分:0)

FileInputStream类直接与底层文件系统一起工作。如果有问题的文件没有在那里存在,它将无法打开它。

getResourceAsStream()方法的工作方式不同。它尝试使用调用它的类的ClassLoader定位和加载资源。这使它能够找到嵌入到jar文件中的资源。

相关问题