How to write to a file in WebContent directory fro

2019-07-27 04:28发布

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.

3条回答
Luminary・发光体
2楼-- · 2019-07-27 05:04

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楼-- · 2019-07-27 05:15

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.

查看更多
闹够了就滚
4楼-- · 2019-07-27 05:17

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.

查看更多
登录 后发表回答