2016-07-28 116 views
0

我有一個問題,我無法解決。 我需要讀取屬性文件,但不能設置正確的路徑。 java.io.File的文檔說我必須從src/... 設置它不工作,我做了一個從當前文件的路徑,並具有相同的問題。如何設置屬性文件的正確路徑?

的例外是:FileNotFound

PropertyReader類:

public final class PropertyReader { 

    private Properties prop = new Properties(); 
    private InputStream input = null; 

    public Properties getProperties(File file) { 
     try { 
      input = new FileInputStream(file); 
      // load a properties file 
      prop.load(input); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (null != input) { 
       try { 
        input.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     return prop; 
    } 
} 

而且ApplicationController.class它採用PropertyReader:由C

@RequestMapping(value = "/result", method = RequestMethod.GET) 
public String resultPage(ModelMap model) { 
    //Getting property with key "path" 
    model.addAttribute("path", new PropertyReader().getProperties(file).getProperty("path")); 
    return "result"; 

如果我設置路徑: // ..它工作正常。

Project structure

謝謝各位大大,有一個愉快的一天!

+0

把屬性的資源文件夾中的文件 –

+0

你是如何創建'文件對象 – Sanjeev

+0

文件文件=新文件(「這裏是文件路徑」); –

回答

0

我用註釋@PropertySource和@Value()

例如解決它:

//There could be any folder @PropertySource("classpath:file.properties") public class AnyClass { //There could be any property @Value("${some.property}") private String someValue; }

0

試着用下面的例子來讀取屬性文件。

import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.Properties; 

public class App { 
    public static void main(String[] args) { 

    Properties prop = new Properties(); 
    InputStream input = null; 

    try { 

     input = new FileInputStream("config.properties"); 

     // load a properties file 
     prop.load(input); 

     // get the property value and print it out 
     System.out.println(prop.getProperty("mysqldb")); 
     System.out.println(prop.getProperty("dbuser")); 
     System.out.println(prop.getProperty("dbpassword")); 

    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } finally { 
     if (input != null) { 
      try { 
       input.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    } 
} 

它還取決於你使用的框架,如SpringMVC,JSF和Struts。所有這些框架都有自己的快捷方式來訪問屬性文件。

+0

我使用的是SpringMVC,無論如何你的答案和我的PropertyReader.class一樣。 –