顯示具有 Java 標籤的文章。 顯示所有文章
顯示具有 Java 標籤的文章。 顯示所有文章

2010年3月3日 星期三

Use Servlet Download File

Source Code Refrence :

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
      
request.setCharacterEncoding("UTF-8");

String filename = (String)request.getParameter("filename");
String original_filename = (String)request.getParameter("original_filename");
                ServletOutputStream op = response.getOutputStream();
                ServletContext context  = getServletConfig().getServletContext();
                String realFileNamePath = context.getRealPath(filename);
    
File f = new File(realFileNamePath);
                int length = 0;
  
                response.setContentType("application/octet-stream");
                response.setContentLength( (int)f.length() );
                response.setHeader( "Content-Disposition",
                                                      "attachment; filename=\"" + original_filename + "\"" );

               byte[] bbuf = new byte[1024];
               DataInputStream in = new DataInputStream(new FileInputStream(f));

               while ((in != null) && ((length = in.read(bbuf)) != -1))
               {
                     op.write(bbuf,0,length);
               }

               in.close();
               op.flush();
               op.close();
}

2010年2月5日 星期五

取得Web Site在Server端真正的路徑

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
   ...
   ServletContext context = getServletContext();
   String path = context.getRealPath("/");
   ...
}

2010年1月12日 星期二

千分號顯示

import java.text.DecimalFormat;

DecimalFormat format2 = new DecimalFormat("###,###,###");

int money = 1000;

String moneyComa = format2.format(money);

System.out.pirntln(moneyComa); //1,000;