Dev Language/JAVA

파일생성 예제

타카스 류지 2015. 2. 24. 11:36

 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
 import java.io.*;
 
 //클래스에 추가할 request
 HttpServletRequest request

 
 //사용하는 함수
 createFileHtml(request.getSession().getServletContext(), releasemanageVoHtml.getCntsId(), releasemanageVoHtml.getMenuId(),releasemanageVoHtml.getCntsSrc());


 /**
  * 배포 html 파일 생성
  */
 public void createFileHtml(ServletContext context,String cntsId,String menuId,String cntsSrc){
 
  //구분자 (/)
  String separatorSymbol = File.separator;
  //최상단 경로부터 하단경로
  String realFolder = context.getRealPath("html/cms");
  //파일명
  String fileName = cntsId + "_" + menuId + ".html";
  //개행문자 치환
  String sCntsSrc = cntsSrc;
  
  sCntsSrc=sCntsSrc.replaceAll("&","&");
  sCntsSrc=sCntsSrc.replaceAll("&lt;","<");
  sCntsSrc=sCntsSrc.replaceAll("&gt;",">");
  //sCntsSrc=sCntsSrc.replaceAll("\n", "<br>");
  sCntsSrc=sCntsSrc.replaceAll(System.getProperty("line.separator"), "<br>");
  sCntsSrc=sCntsSrc.replaceAll("&nbsp;"," ");  //공백
  sCntsSrc=sCntsSrc.replaceAll("&quot;", "\""); //"(더블 쿼테이션)
   
  try {
   
         File targetFile = new File(realFolder + separatorSymbol + fileName);
        
         targetFile.createNewFile();
        
         BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile.getPath()), "UTF8"));
        
         output.write(sCntsSrc);
        
         output.close();
        
     } catch(UnsupportedEncodingException uee) {
         uee.printStackTrace();
     } catch(IOException ioe) {
         ioe.printStackTrace();
     }
 
 }