2017-07-10 7 views
0

ユーザーは、txt拡張子を持つファイルを自分のシステムにアップロードします。このファイルにアクセスできるようにしますwww.exp.com/text_file.txtファイルをwebappフォルダにアップロードします。

私はそれを行うことができませんでした。 Project/src/main/webapp/text_file.txt、私はwebappの下にファイルをドロップすると私はそれを得ることができます。 しかし、webappにtxtファイルを作成するにはどうしたらいいですか?

new File(---); - >このコードは私が望むものではありません。それはeclipseフォルダの下に作成されます。

Project 
     ->pom.xml 
     ->src 
      ->main 
        ->java 
        ->resources 
        ->webapp 
          ->WEB-INF 

答えて

0

あなたは、サーブレットを使用している、このコードは:)(のは、Webアプリケーション/リソースにファイルを置いてみましょう)それが動作

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { 

     // Getting ServletContext from request 
     ServletContext ctx= req.getServletContext(); 
     // Get the absolute path of the file 
     String filename = ctx.getRealPath("resources/file.text"); 
     // getting mimeType of the file 
     String mime = ctx.getMimeType(filename); 
     // Error handling 
     if (mime == null) { 
     res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
     return; 
     } 

     // Setting MIME content type 
     res.setContentType(mime); 
     // Getting file object 
     File file = new File(filename); 
     // Setting content length header 
     res.setContentLength((int)file.length()); 

     // FileInputStream to read from file 
     FileInputStream in = new FileInputStream(file); 
     // Obtain OutputStream from response object 
     OutputStream out = res.getOutputStream(); 

     // Writing to the OutputStream 
     byte[] buffer = new byte[1024]; 
     int bytes = 0; 
     // we stop when in.read returns -1 and read untill it does not 
     while ((bytes = in.read(buffer)) >= 0) { 
     out.write(buffer, 0, count); 
     } 
    // Clean up, closing resources 
    out.close(); 
    in.close(); 

} 
+0

おかげで動作するはずと仮定すると、私は私が変更されたときに、このテキストファイルは削除する理由を理解しませんプロジェクトを開き、Ctrl + Sを押してください – cezaalp

+0

削除するとはどういう意味ですか? – fg78nc

+0

サーブレットファイルを変更して保存すると、作成されたテキストファイルが削除されます。 – cezaalp

関連する問題