레이블이 프로그래밍인 게시물을 표시합니다. 모든 게시물 표시
레이블이 프로그래밍인 게시물을 표시합니다. 모든 게시물 표시

2012-10-31

java Framework/java] 파일 이어받기 기능 구현



출처 :http://webprogrammer.tistory.com/tag/%EC%9E%90%EB%B0%94%EC%97%90%EC%84%9C%20%ED%8C%8C%EC%9D%BC%20%EC%9D%B4%EC%96%B4%EB%B0%9B%EA%B8%B0%20%EA%B8%B0%EB%8A%A5


자바에서 파일 쓰기 할 때
          BufferedWriter file = new BufferedWriter(new FileWriter("filename"));
대개의 경우 이런식으로 코딩을 했었는데, 이 코드는 파일을 덮어쓴다.
파일을 덮어쓰지 않고 이어쓰기하는 방법이 없을까 하고 고민하고 찾아봤다.
RandomAccessFile 클래스를 사용하는 방법도 있었고
그리고 파일을 쭉 읽어서 변수에 저장을 한 뒤 새로 추가할 내용을 덧붙여서 파일에 쓰는 방법도 있었다.
하지만 뭔가 더 간편한게 있을 것 같아서 찾아봤더니
이 한문장이면 파일 이어쓰기가 가능하다.

        BufferedWriter file = new BufferedWriter(new FileWriter("filename", true));

이 코드는 파일이 없으면 새로 만들고 있다면 덮어쓰지 않고 이어서 쓰게한다.

그리고 파일에서 개행문자를 쓰려고할 때
C나 C++에서처럼 당연히 ""이 먹힐거라 생각을 하고
          str = str + "";
          file.write(str, 0, str.length());
이렇게 썼는데 파일에는 줄바꿈이 되어있지 않았다.
알아본 결과 저 위에서 사용한 FileWriter가 가독성때문에 ""을 지원하지 않기 때문이었다.
BufferedWriter를 통해서 개행문자를 쓸 수 있다.
바로 이렇게..

        file.write(str, 0, str.length());
        file.newLine();

간단하다. 하하하;;;
이 사실을 난... 어제 알았다. 쿨럭 -_-;;;
까먹을까봐...

-------------------------------

기존파일에 덧붙여서 내용을 저장하려면, RandomAccessFile 클래스를 사용해야 합니다.
아래는 간단한 예제 입니다.

출처 : http://finetia.egloos.com/1422965
—————————————————————————
import java.io.IOException;
import java.io.RandomAccessFile;
public class UsingFile {
  public UsingFile() {
  }
  public static void main(String[] args) {
    try {
      String name = “c:\\tmpfile.txt”;
      RandomAccessFile raf = new RandomAccessFile(name, “rw”);
      raf.seek(raf.length());
      raf.writeBytes(“\r\n append”);
    }
    catch (IOException e) {
      System.out.println(“Error opening file: ” + e);
    }
  }
}


출처 : http://rothmans.wordpress.com/2006/07/12/%EC%86%8C%EC%8A%A4%ED%8C%8C%EC%9D%BC-%EC%9D%B4%EC%96%B4-%EC%93%B0%EA%B8%B0/

java] SimpleDateFormate 예제



출처 : http://www.ssial.com/141


import java.text.SimpleDateFormat;

.
.
.


Format formatter;
 
    // The year
    formatter = new SimpleDateFormat("yy");    // 02
    formatter = new SimpleDateFormat("yyyy");  // 2002
 
    // The month
    formatter = new SimpleDateFormat("M");     // 1
    formatter = new SimpleDateFormat("MM");    // 01
    formatter = new SimpleDateFormat("MMM");   // Jan
    formatter = new SimpleDateFormat("MMMM");  // January
 
    // The day
    formatter = new SimpleDateFormat("d");     // 9
    formatter = new SimpleDateFormat("dd");    // 09
 
    // The day in week
    formatter = new SimpleDateFormat("E");     // Wed
    formatter = new SimpleDateFormat("EEEE");  // Wednesday
 
    // Get today's date
    Date date = new Date();
 
    // Some examples
    formatter = new SimpleDateFormat("MM/dd/yy");
    String s = formatter.format(date);
    // 01/09/02
 
    formatter = new SimpleDateFormat("dd-MMM-yy");
    s = formatter.format(date);
    // 29-Jan-02
 
    // Examples with date and time; see also
    // e316 Formatting the Time Using a Custom Format
    formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
    s = formatter.format(date);
    // 2002.01.29.08.36.33
 
    formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
    s = formatter.format(date);
    // Tue, 09 Jan 2002 22:14:02 -0500

    // The hour (1-12)
    formatter = new SimpleDateFormat("h");     // 8
    formatter = new SimpleDateFormat("hh");    // 08
 
    // The hour (0-23)
    formatter = new SimpleDateFormat("H");     // 8
    formatter = new SimpleDateFormat("HH");    // 08
 
    // The minutes
    formatter = new SimpleDateFormat("m");     // 7
    formatter = new SimpleDateFormat("mm");    // 07
 
    // The seconds
    formatter = new SimpleDateFormat("s");     // 3
    formatter = new SimpleDateFormat("ss");    // 03
 
    // The am/pm marker
    formatter = new SimpleDateFormat("a");     // AM
 
    // The time zone
    formatter = new SimpleDateFormat("z");     // PST
    formatter = new SimpleDateFormat("zzzz");  // Pacific Standard Time
    formatter = new SimpleDateFormat("Z");     // -0800
 
    // Get today's date
    Date date = new Date();
 
    // Some examples
    formatter = new SimpleDateFormat("hh:mm:ss a");
    String s = formatter.format(date);
    // 01:12:53 AM
 
    formatter = new SimpleDateFormat("HH.mm.ss");
    s = formatter.format(date);
    // 14.36.33



출처: http://www.exampledepot.com/egs/java.text/pkg.html#Times

java] random 사용하여 난수 구하기.



    // 1 ~ 10  사이의 정수 난수
    for (int i = 1; i <= 20; i++) {
      int n = (int) (Math.random() * 10) + 1;   <== *10 부분을 100, 1000 으로 늘리면 1-100, 1-1000 까지의 난수를 구할 수 있다.
      System.out.println(n);
    }

    // 0.0 ~ 1.0    사이의 실수 난수
    for (int i = 1; i <= 20; i++)
      System.out.println(Math.random());

java] Quartz를 사용하여 동적으로 Job 등록하기




출처 : http://zemba.tistory.com/53


Quartz는 작업을 일정 지정한 시간에 Class기능을 수행하도록 만드는 스케쥴러이다.
이를 위해서는  Schduler가 있어야 하며 또 수행할 작업들의 Class가 있어야 한다.

나는 Quartz를 사용하기 위해서 우선 다음과 같이 분류하였다.



분류
 기능
 Quartz Scheduler Main
 실질적인 Scheduler가 Job을 수행시키는 Class
 Quartz Job Class
 수행할 작업의 내용이 담겨있는 Class
 Quartz PropertyLoader
 Properties에 Job정보를 Main Class에서 읽어 드리도록만든 Loader Class(정해진 규칙에 따라서 등록해야 함)
각 분류별 Class의 코드의 내용을 확인해보자.
1.Scheduler Class(THJobMain.class)
  - Main에서는 Properties파일에서 등록한 Job내용을 읽어드려 수행하는 작업만 수행한다.
  - Scheduler는 StdSchedulerFactory에 스케쥴생성을 통하여 스케쥴러를 시작할수 있다. 단순히 스케쥴러는 시작만한다.
  - 스케쥴러 에서 Start후에는 스케쥴러에 등록된 Job Class가 동작하게 되는것이다.
  - JobRegist에서 Job을 등록해준다.
  - JobRegist에서는 CronTrigger를 사용하여 스케쥴에 등록하여준다.
  - JobDetail은 "Name" , "Group" , "Class" 형태로 등록하고
    CronTrigger는 "Name" , "Group" , "CronExpression"으로 등록한다.
  - 해당 Job을 scheduler.scheduleJob(jobDetail, trigger); 를 사용하여 스케쥴러에 등록해준다.
package tahoe.core.job;import java.text.ParseException;
import org.apache.log4j.PropertyConfigurator;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class THJobMain
{
    private SchedulerFactory schedulFactoty = null;
    private Scheduler scheduler = null;
    private JobDetail jobDetail = null;
    private CronTrigger trigger = null;
    private String className = null;
    private String expression = null;
    THPropertyLoader ThProp = new THPropertyLoader();
  
    public THJobMain()
    {
        JobInit();
    }
 
    private void JobInit()
    {
        try
        {
            schedulFactoty = new StdSchedulerFactory();
            scheduler = schedulFactoty.getScheduler();
            scheduler.start();
            JobRegist();
        }
        catch (SchedulerException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void JobRegist()
    {
        String taskGroups = ThProp.read("TaskGroups");
        String taskList = ThProp.read( taskGroups + ".TaskNames");
        String[] arTaskGroups = taskList.split(",");
     
        for ( int i = 0; i < arTaskGroups.length; i++ )
        {
            Class c = null;
            className = ThProp.read( arTaskGroups[i] + ".class" );
            expression = ThProp.read( arTaskGroups[i] + ".Expression" );

            try
            {
                c = Class.forName( className );
            }
            catch (ClassNotFoundException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jobDetail = new JobDetail( arTaskGroups[i], arTaskGroups[i], c );
            trigger = new CronTrigger( arTaskGroups[i], arTaskGroups[i] );
            try
            {
                trigger.setCronExpression( expression );
                scheduler.scheduleJob(jobDetail, trigger);
            }
            catch (SchedulerException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch ( ParseException e2 )
            {
                e2.printStackTrace();
            }
        }
    }
 
 
    public static void main(String[] args)
    {
        PropertyConfigurator.configure("WEB-INF/conf/log4j.properties");
        new THJobMain();
    }
}


2.PropertyLoader Class(THPropertyLoader.class)
  - Param으로 받은 string Value를 사용하여 Properties파일의 해당 내용을 찾는다.
  - String으로 값을 Return해준다.
package tahoe.core.job

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class THPropertyLoader
{
 
    public THPropertyLoader()
    {}
 
    /**
     * properties 파일 읽기
     */
     public String read(String propKey)
     {
         Properties  pp  = new Properties();
         try
         {
              FileInputStream fis  = new FileInputStream("WEB-INF/conf/quartz.properties");
              pp.load(fis);
         }
         catch (IOException ioe)
         {
              ioe.printStackTrace();
              System.exit(-1);
         }
        return pp.getProperty(propKey);
     }
}


3.Job Class(THJobTest1.class,THJobTest2.class,THJobTest3.class)
  - 실재 스케쥴이 시작될때 작업을 해야할 기능이 있는 Class이다.
  - Job Class는 Quartz의 Job class를 필수적으로 구현해서 사용해야한다.(implement Job)
  - Job 수행은 execute를 통해서 실행된다.(로직을 사용시에 이부분에서 로직을 구현하면 된다.)
  - Test를 위해 sysout메세지 출력으로 Test해본다.
public class THJobTest1 implements Job
{
    public void execute(JobExecutionContext context)
    {
        System.out.println("Test Job1 = " + new Date());
    }
}
public class THJobTest2 implements Job
{
    public void execute(JobExecutionContext context)
    {
        System.out.println("Test Job2 = " + new Date());
    }
public class THJobTest3 implements Job
{
    public void execute(JobExecutionContext context)
    {
        System.out.println("Test Job3 = " + new Date());
    }
}


이제 Properties파일에 설정한후 실행을 해보자.
현재 Property에 Expression 설정을 매 5초 마다 실행 하도록 설정하였다.
각각 등록후 에 Main에서 수행시킬 경우 다음과 같이 내용이 출력되었다.
이로써 Job Class를 작성한후 매번 Main에서 Job을 등록하지 않아도 Properties파일을 사용하여 작업스케쥴러를
등록하여 편리하게 사용할 수 있다.
[2010:06:15 11:06:58][INFO][org.quartz.simpl.SimpleThreadPool][0(ms)][Tahoe]-Job execution threads will use class loader of thread: main
[2010:06:15 11:06:58][INFO][org.quartz.core.SchedulerSignalerImpl][0(ms)][Tahoe]-Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
[2010:06:15 11:06:58][INFO][org.quartz.core.QuartzScheduler][0(ms)][Tahoe]-Quartz Scheduler v.1.7.3 created.
[2010:06:15 11:06:58][DEBUG][org.quartz.utils.UpdateChecker][0(ms)][Tahoe]-Checking for update...
[2010:06:15 11:06:58][INFO][org.quartz.simpl.RAMJobStore][0(ms)][Tahoe]-RAMJobStore initialized.
[2010:06:15 11:06:58][INFO][org.quartz.impl.StdSchedulerFactory][0(ms)][Tahoe]-Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
[2010:06:15 11:06:58][INFO][org.quartz.impl.StdSchedulerFactory][0(ms)][Tahoe]-Quartz scheduler version: 1.7.3
[2010:06:15 11:06:58][INFO][org.quartz.core.QuartzScheduler][0(ms)][Tahoe]-Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
[2010:07:15 11:07:00][DEBUG][org.quartz.simpl.SimpleJobFactory][0(ms)][Tahoe]-Producing instance of Job 'THJobTest1.THJobTest1', class=tahoe.core.job.THJobTest1
[2010:07:15 11:07:00][DEBUG][org.quartz.core.JobRunShell][0(ms)][Tahoe]-Calling execute on job THJobTest1.THJobTest1
[2010:07:15 11:07:00][DEBUG][org.quartz.simpl.SimpleJobFactory][0(ms)][Tahoe]-Producing instance of Job 'THJobTest2.THJobTest2', class=tahoe.core.job.THJobTest2
[2010:07:15 11:07:00][DEBUG][org.quartz.core.JobRunShell][0(ms)][Tahoe]-Calling execute on job THJobTest2.THJobTest2
[2010:07:15 11:07:00][DEBUG][org.quartz.simpl.SimpleJobFactory][0(ms)][Tahoe]-Producing instance of Job 'THJobTest3.THJobTest3', class=tahoe.core.job.THJobTest3
[2010:07:15 11:07:00][DEBUG][org.quartz.core.JobRunShell][0(ms)][Tahoe]-Calling execute on job THJobTest3.THJobTest3
Test Job3 = Mon Mar 15 11:07:00 KST 2010
Test Job1 = Mon Mar 15 11:07:00 KST 2010
Test Job2 = Mon Mar 15 11:07:00 KST 2010
[2010:07:15 11:07:01][DEBUG][org.quartz.utils.UpdateChecker][0(ms)][Tahoe]-No update found.
[2010:07:15 11:07:05][DEBUG][org.quartz.simpl.SimpleJobFactory][0(ms)][Tahoe]-Producing instance of Job 'THJobTest1.THJobTest1', class=tahoe.core.job.THJobTest1
[2010:07:15 11:07:05][DEBUG][org.quartz.core.JobRunShell][0(ms)][Tahoe]-Calling execute on job THJobTest1.THJobTest1
Test Job1 = Mon Mar 15 11:07:05 KST 2010
[2010:07:15 11:07:05][DEBUG][org.quartz.simpl.SimpleJobFactory][0(ms)][Tahoe]-Producing instance of Job 'THJobTest2.THJobTest2', class=tahoe.core.job.THJobTest2
[2010:07:15 11:07:05][DEBUG][org.quartz.core.JobRunShell][0(ms)][Tahoe]-Calling execute on job THJobTest2.THJobTest2
Test Job2 = Mon Mar 15 11:07:05 KST 2010
[2010:07:15 11:07:05][DEBUG][org.quartz.simpl.SimpleJobFactory][0(ms)][Tahoe]-Producing instance of Job 'THJobTest3.THJobTest3', class=tahoe.core.job.THJobTest3
[2010:07:15 11:07:05][DEBUG][org.quartz.core.JobRunShell][0(ms)][Tahoe]-Calling execute on job THJobTest3.THJobTest3
Test Job3 = Mon Mar 15 11:07:05 KST 2010

java Framework/java] PDF 작업 관련 url





  •   iText 에서 장평 처리 
    • iText의 예제 소스 중 part/chapter14/TextStateOperateors.java 의 59-62 줄 사이의 canvas.setHorizontalScaling(50) 으로 조정 가능(이미지로 처리하는 듯 함) 
  • 거니네(iText관련 문서/강좌??) http://guni.loveyust.net/tag/itext


      iText.jar :    iText-5.0.5.jar



pdfContentByte 에서 bold 를 사용할 수 있는 방법??
.
// first define a standard font for our text
Font helvetica8BoldBlue = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, Color.blue);

// create a column object
ColumnText ct = new ColumnText(cb);

// define the text to print in the column
Phrase myText = new Phrase("Lorem ipsum dolor sit amet, ...", helvetica8BoldBlue);
ct.setSimpleColumn(myText, 72, 600, 355, 317, 10, Element.ALIGN_LEFT);
ct.go();

java Framework/java] Object와 JSONObject


[다운]
Java에서 Json 객체로 변환할 때, json-lib라는 오픈 소스를 이용한다.
http://json-lib.sourceforge.net

json-lib에서 array를 변환할 때는 EZMorph 라이브러리가 필요하다.
http://ezmorph.sourceforge.net

자바스크리브에서 객체를 json 객체로 변환시에는 json.js를 이용한다.
http://json.org

[사용법]
Java에서 Json-lib를 사용하기 위해서 필요한 라이브러리는 다음과 같고, eclipse 사용시 Build Path -> Add Exeternal Archives 에 추가한다.
json-lib-2.1-jdk15.jar
jakarta commons-lang 2.3
 
jakarta commons-beanutils 1.7.0  

jakarta commons-collections 3.2  

jakarta commons-logging 1.1

ezmorph 1.0.4

[예제]
   1. 자바스크립트에서
      object.toJSONString();

   2. 자바에서
      JSONObject oJSONObject = JSONObject.fromObject( object );
      JSONArray = JSONArray.fromObject( retlist );

json형식 ==>{"jsontest":[{"name":"Mr.Cho","location":"Seoul"}]}

import java.util.Iterator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JSONParse {
   public static void main(String[] ar) {
      String s = "{\"jsontest\":[{\"name\":\"Mr.Cho\",\"location\":\"Seoul\"}]}";
      JSONObject jo = JSONObject.fromObject(s);
      JSONArray ja = jo.getJSONArray("jsontest");
      for (Iterator i = ja.iterator(); i.hasNext();) {
          JSONObject ob = (JSONObject) i.next();
          String a = ob.getString("name");
          String b = ob.getString("location");
          System.out.println(a);
          System.out.println(b);
      }
   }
}



아래 fromObject를 사용할 수 있어서 json.jar (org.json.JSONObject) 보다는 json-lib.jar (net.sf.json.JSONObject) 이 더 편한 것 같다.
JSONObject.fromObject( obj )
obj에 문자열도 가능하며, 이것이 JSONText 규칙에 맞을 경우 적절한 JSON 객체를 만들어준다.
이때, obj에 있는 문자열은 작은따옴표(')도 문자열로 간주한다.

   Map states = JSONObject.fromObject("{'':'선택안함','1':'신청','2':'완료','3':'보류'}")

위와 같이 하면 꽤 깔쌈하게 Map 객체를 만들 수 있으며, 이를 Velocity에서도 #set 구문을 이용해서 똑같이 쓸 수도 있다.

java] jsp jdbc 연결 예제




출처  : http://allinfo.tistory.com/14


파일명 : jdbctest.jsp

<%@ page contentType="text/html;charset=euc-kr" import="java.sql.*" %>
<% request.setCharacterEncoding("euc-kr"); %>
<%
 // 데이터베이스 연결관련 변수 선언
 Connection conn = null;
 Statement stmt = null;
 // 데이터베이스 연결관련정보를 문자열로 선언
 String jdbc_driver = "oracle.jdbc.driver.OracleDriver";
 String jdbc_url = "jdbc:oracle:thin:@localhost:1521:ORCL";

 try{
  // JDBC 드라이버 로드
  Class.forName(jdbc_driver);
  // 데이터베이스 연결정보를 이용해 Connection 인스턴스 확보
  conn = DriverManager.getConnection(jdbc_url,"scott","tiger");
  // Connection 클래스의 인스턴스로 부터 SQL  문 작성을 위한 Statement 준비
  stmt = conn.createStatement();
  // username 값을 입력한 경우 sql 문장을 수행.
if(request.getParameter("username") != null) {
   String sql = "insert into jdbc_test values('"+request.getParameter("username")+"','"+request.getParameter("email")+"')";
   stmt.executeUpdate(sql);
  }
 }
 catch(Exception e) {
  System.out.println(e);
 }
%>
<HTML>
<HEAD><TITLE>JDBC 테스트 </TITLE></HEAD>
<BODY>
<center>
<H2>이벤트 등록</H2>
<HR>
<form name=form1 method=post action=jdbctest.jsp>
등록이름 : <input type=text name=username>
email주소 : <input type=text name=email size=20>
<input type=submit value="등록">
</form>
<HR>
</center>
# 등록 목록<P>
<%
 try{
  // select 문장을 문자열 형태로 구성한다.  String sql = "select username, email from jdbc_test";
  // select 를 수행하면 데이터정보가 ResultSet 클래스의 인스턴스로 리턴됨.  ResultSet rs = stmt.executeQuery(sql);
  int i=1;
  // 마지막 데이터까지 반복함.  while(rs.next()) {
   out.println(i+" : "+rs.getString(1)+" , "+rs.getString("email")+"<BR>");
   i++;
  }
  // 사용한 자원의 반납.
  rs.close();
  stmt.close();
  conn.close();
 }
 catch(Exception e) {
  System.out.println(e);
 }
%>
</BODY>
</HTML>

2012-09-19

javascript] 숫자만 입력받는 함수


회원으로 가입하거나 할때 유용하게 쓰일수 있는 팁이라서 올린다.[초기값 한글/영문으로 지정하기]<input type="text" name="m_name" style="ime-mode:active;"> //초기값이 한글자판
<input type="text" name="m_id" style="ime-mode:inactive;"> //초기값이 영문자판



[숫자 및 특수문자 허용]
// 숫자만 입력받는다. 특수문자('-','.',...)도 허용한다.
function onlyNumber() {
if((event.keyCode > 31) && (event.keyCode < 45) || (event.keyCode > 57)) {
event.returnValue = false;
}
}

// 숫자만 입력받는다. "-"도 받지않는다.
function onlyNumber2(loc) {
if(/[^0123456789]/g.test(loc.value)) {
alert("숫자가 아닙니다.\n\n0-9의 정수만 허용합니다.");
loc.value = "";
loc.focus();
}
}

사용예제) - 주민번호나 전화번호 경우<input name="jumin2" value="" type="text" size="7" maxlength="7" onKeyPress=onlyNumber() onBlur=onlyNumber2(this);>