Java 从属性文件读取文件路径
我试图从从属性读取的文件路径中读取文件,但我一直得到FileNotFoundException(该文件存在) test.properties:Java 从属性文件读取文件路径,java,file-io,properties,Java,File Io,Properties,我试图从从属性读取的文件路径中读取文件,但我一直得到FileNotFoundException(该文件存在) test.properties: test.value = "src/main/resources/File.csv" LoadProperties.java: public class LoadProperties { public static void main(String[] args) throws FileNotFoundException, IOExceptio
test.value = "src/main/resources/File.csv"
LoadProperties.java:
public class LoadProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties aProp = new Properties();
aProp.load(new FileInputStream("src/main/resources/test.properties")); // works
String filepath = aProp.getProperty("test.value");
System.out.println(filepath); // outputs: "src/main/resources/File.csv"
FileReader aReader = new FileReader("src/main/resources/File.csv"); // works
FileReader aReader2 = new FileReader(filepath); // java.io.FileNotFoundException
}
}
为什么在上面的行正常工作时抛出此异常?
我应该如何从带有属性的路径读取文件?您不应该在属性文件中放入“文件”。在这里,Java将其视为:
String file = "\"src/main/resources/File.csv\"";
你不应该在你的财产档案中写“你的财产”。在这里,Java将其视为:
String file = "\"src/main/resources/File.csv\"";
属性文件中不需要双引号来表示连续字符串
属性文件中不需要双引号来表示连续字符串。您可以编写自己的逻辑来读取属性文件,无论文件路径中是否有单引号或双引号
String propertyFileLocation = "C:\a\b\c\abc.properties";
try
{
fileInputStream = new FileInputStream(propertyFileLocation);
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
properties = new Properties();
String currentLine = null;
String[] keyValueArray = null;
while ((currentLine = bufferedReader.readLine()) != null) {
if (!currentLine.trim().startsWith("#")) {
keyValueArray = currentLine.split("=");
if (keyValueArray.length > 1) {
properties.put(keyValueArray[0].trim(), keyValueArray[1].trim().replace("\\\\","\\"));
}
}
}
}
catch (Exception e)
{
return null;
}
您可以编写自己的逻辑来读取属性文件,无论文件路径中是否有单引号或双引号
String propertyFileLocation = "C:\a\b\c\abc.properties";
try
{
fileInputStream = new FileInputStream(propertyFileLocation);
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
properties = new Properties();
String currentLine = null;
String[] keyValueArray = null;
while ((currentLine = bufferedReader.readLine()) != null) {
if (!currentLine.trim().startsWith("#")) {
keyValueArray = currentLine.split("=");
if (keyValueArray.length > 1) {
properties.put(keyValueArray[0].trim(), keyValueArray[1].trim().replace("\\\\","\\"));
}
}
}
}
catch (Exception e)
{
return null;
}