开发者

How to create file in current system from within Grails controller action and save data fetched from database?

In my Grails application I need to create a file in current system in which I need to save information fetched from table in database. How to do this from within controller action? I don't have any idea of it.

I have created file as

File file=new File("file name.txt") 

file.createNew开发者_高级运维File();

then I have wrote values of MySQL database table fields in it as:

file<<patient.id
file<<patient.name
.
.
.

it stores data like continuous text but I want to have a .doc file in which data should get stored in table. I found Apache's POI for creating doc file but I am not getting how it works and how I should use it.


Not sure exactly what you want to store in a file but below is an example of how to easly write a String to a file using Apache-commons-io Which should be included in grails

import org.apache.commons.io.FileUtils;

    class SomeController{

        def writeToFile = {

           def data = getSomeStringData();

           def fileStore = new File("./path/to/files/ControllerOutput_${new Date()}.txt");
           fileStore.createNewFile();


           FileUtils.writeStringToFile(fileStore, data);

           println("your file was created @ {fileStore.absolutePath} and is ${fileStore.length()} bytes");


        }

    }

Does this help? If not, you need to explain exactly what your looking for.


This is a comment to Michael's answer (unfortunately I still don't have the reputation to reply on answers).

If you're struggling around the problem how to specifiy the relative path from within your controller's context, this might help you: So if you have following folder you want to read/write files from/into"..

/myproject/web-app/temp/

you can access the file like this:

import org.codehaus.groovy.grails.commons.ApplicationHolder as AH

// getResource references to the web-app folder as root folder
Resource resource = AH.getApplication().getParentContext().getResource("/temp/myfile.txt) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜