How to write to a file in WebContent directory from a class in WEB-INF/classes directory

我们两清 提交于 2019-12-11 14:01:14

问题


I have a Java Class UpdateStats in WEB-INF/Classes directory of a dynamic web application.This class has a function writeLog() which writes some logs to a text file.I want this text file to be in webcontent directory.Thus everytime the function is called updates stats are written in that text file. The problem is how to give the path of that text file in webcontent directory from within that function,which resides in WEB-INF/Classes directory.


回答1:


You can get your webapp root directory from ServletContext:

String path = getServletContext().getRealPath("WEB-INF/../");
File file = new File(path);
String fullPathToYourWebappRoot = file.getCanonicalPath();

Hope this helps.




回答2:


You can do something like below in your servlet,

When you do getServletContext().getRealPath() and put some string argument the file will see at your webcontent location. If you want something into WEB-INF, you can give fileName like "WEB-INF/my_updates.txt".

    File update_log = null;
final String fileName = "my_updates.txt";

@Override
public void init() throws ServletException {
    super.init();
    String file_path = getServletContext().getRealPath(fileName);
    update_log = new File(file_path);
    if (!update_log.exists()) {
        try {
            update_log.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error while creating file : " + fileName);
        }
    }
}

public synchronized void update_to_file(String userName,String query) {

    if (update_log != null && update_log.exists()) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(update_log, true);
            fos.write((getCurrentFormattedTime()+" "+userName+" "+query+"\n").getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}



回答3:


To write a file you need to know absolute path of your web content directory on server as file class require absolute path.

File f = new File("/usr/local/tomcat/webapps/abc/yourlogfile.txt");
FileOutputStream out = new FileOutputStream(f);
out.writeLog("Data");

Assumption : abc is your project name

WebContent is not any directory when you deploy application. All files under web content goes directly under project name.



来源:https://stackoverflow.com/questions/16846080/how-to-write-to-a-file-in-webcontent-directory-from-a-class-in-web-inf-classes-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!