how to read a file from server in play framework

前端 未结 4 2069
悲哀的现实
悲哀的现实 2021-02-07 13:16

I have the following file

/app/menus/menu1.yml

and I\'d like to read it\'s contents

--

short answer:

fileConten         


        
相关标签:
4条回答
  • 2021-02-07 13:47

    For Play 2.0 in Scala you want to use Play.getFile(relativePath: String)

    0 讨论(0)
  • 2021-02-07 13:52

    Play includes the SnakeYAML parser. From their docs:

    Yaml yaml = new Yaml();
    String document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae";
    List<String> list = (List<String>) yaml.load(document);
    System.out.println(list);
    

    ['Hesperiidae', 'Papilionidae', 'Apatelodidae', 'Epiplemidae']

    There is also a version of Yaml.load that takes an InputStream, which is demonstrated in this sample code: http://code.google.com/p/snakeyaml/source/browse/src/test/java/examples/LoadExampleTest.java

    0 讨论(0)
  • 2021-02-07 13:55

    PlayFramework is built using the Java language.

    In your code, there is no restriction about the usage of the java API. So, your file can be read using the standard java code, if you know the file absolute path:

    java.io.File yourFile = new java.io.File("/path/app/menus/menu1.yml");
    java.io.FileReader fr = new java.io.FileReader(yourFile);
    // etc.
    

    If you want to access a File in a relative path from your Play application, your can use the play "VirtualFile" class: http://www.playframework.org/documentation/api/1.1/play/vfs/VirtualFile.html

    VirtualFile vf = VirtualFile.fromRelativePath("/app/menus/menu1.yml");
    File realFile = vf.getRealFile();
    FileReader fr = new FileReader(realFile);
    // etc.
    
    0 讨论(0)
  • 2021-02-07 13:58

    From Play 2.6 this is now in Environment. And I suggest using either .getExistingFile which returns an option in case file does not exist. Or .resource which returns a URL to anything in the classpath only.

    https://www.playframework.com/documentation/2.6.x/api/scala/index.html#play.api.Environment

     class Someclass @Inject (environment: play.api.Environment) {
     // ...
    
     environment.getExistingFile("data/data.xml").fold{
       // NO FILE. PANIC
     }{ file =>
       // Do something magic with file
     }
    
    0 讨论(0)
提交回复
热议问题