opensas
opensas

Reputation: 63525

how to read a file from server in play framework

I have the following file

/app/menus/menu1.yml

and I'd like to read it's contents

--

short answer:

fileContent = play.vfs.VirtualFile.fromRelativePath("/app/menus/menu1.yml").contentAsString();

Upvotes: 14

Views: 13854

Answers (4)

flurdy
flurdy

Reputation: 3972

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
 }

Upvotes: 1

tksfz
tksfz

Reputation: 2970

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

Upvotes: 11

Brad Mace
Brad Mace

Reputation: 27886

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

Upvotes: 2

Benoit Courtine
Benoit Courtine

Reputation: 7064

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.

Upvotes: 16

Related Questions