2016-07-28 15 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を使用しています。

@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"; 

私はCからのパスを設定していた場合: // ..うまく動作します。

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と同じ回答です。 –

関連する問題