1

動的 Web アプリケーションの WEB-INF/Classes ディレクトリに Java クラス UpdateStats があります。このクラスには、いくつかのログをテキスト ファイルに書き込む関数 writeLog() があります。関数は更新統計と呼ばれ、そのテキスト ファイルに書き込まれます。問題は、WEB-INF/Classes ディレクトリにあるその関数内から webcontent ディレクトリ内のそのテキスト ファイルのパスを指定する方法です。

4

3 に答える 3

0

サーブレットで以下のようなことができます。

いくつかgetServletContext().getRealPath()の文字列引数を入力すると、ファイルは Web コンテンツの場所に表示されます。WEB-INF に何かを入れたい場合は、「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();
                }
            }
        }
    }
}
于 2013-05-31T13:58:55.497 に答える
-1

ファイル クラスには絶対パスが必要なため、ファイルを書き込むには、サーバー上の Web コンテンツ ディレクトリの絶対パスを知る必要があります。

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

仮定:abcはあなたのプロジェクト名です

アプリケーションをデプロイするとき、WebContent はディレクトリではありません。Web コンテンツの下のすべてのファイルは、プロジェクト名の直下に配置されます。

于 2013-05-31T06:36:22.093 に答える