Java 文件位置异常

问题描述 投票:0回答:1

有没有办法在 ENV 中设置目录位置并添加文件名并传递它?

我需要解决我所看到的错误

// I am setting a file in the directory pointed by ENV
String fileLoc = System.getenv("PUBLIC");
System.out.println("File loc is " + fileLoc); // This prints the loc

// File path is passed as parameter
File file = new File(fileLoc + "\\Public Documents\\testFile.txt"); // file is not null. 

// This throws exception C:\Users\Public\Public Documents\testFile.txt 
// (The system cannot find the path specified)
BufferedReader br = new BufferedReader(new FileReader(file));

// when I do this it works 
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Public\\Public Documents\\testFile.txt"));
java bufferedreader filereader
1个回答
0
投票

其中一个是

C:\\Users\\Public\\Documents\\testFile.txt
,这是正确的路径,另一个是
C:\Users\Public\Public Documents\testFile.txt
(注意公共和空间的重复)

所以要回答,只需将

File file = new File(fileLoc + "\Public Documents\testFile.txt");
更改为
File file = new File(fileLoc + "\\Documents\\testFile.txt");

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.