01. ServerSocket 과 Socket 간의 채팅 소스
02. Swing에서 이미지 아이콘 삽입 및 종료
03. RMI 정상적인 예제
04. RMI registry 등록하지 않고 사용
05. RMI 통신법
06. Directory 찾아서 리스트 만들기
07. IO 관련 소스
08. 파일을 읽는 소스
09. 입력받은 파일을 읽는 소스
10. 스트링을 파일로 저장하는 소스
11. 파일을 저장하는 소스
12. 에디터에는 볼 수 없으나 도스에서는 보임
13. Properties 파일에 관련된 소스
14. 파일과 관련해서 Properties 에서 읽어 오는 소스
15. 읽은 파일입력 후 내용확인하는 소스
16. 입력파일과 저장할 파일을 쓰는 소스
17. 파일을 읽어서 보여주는 소스
18. 2초마다 출력하는 쓰레드 소스
19. 배열과 관련하여
20. 배열로 합계 평균을 내는 소스
21. 프로그램 인수를 받아 평균과 총계를 보여주는 소스
22. 실행되지 않으나 참고해야 할 소스
23. 데이터베이스 커넷션하고 로그파일을 만듬
24. 엔터키를 두르면 검색하는 소스
25. 날짜 포맷 바꾸는 방법
26. Random 클래스로 가져온 값을 중복체크하기
27. TripleDES 을 이용한 암호화 알고리즘
28. MD5로 암호화 하는 알고리즘 (Base64 필요)
29. 버블 소트로 데이타 정렬
30. Random 함수로 받은 값을 중복 체크하는 소소
31. 날짜 관련 함수 이용
32. 특수문자 제거 메소드
33. 암호와 알고리즘을 사용후 복호화 하는 소스와 적용예
34. 특정 폴더에 쌓이는 파일을 없애는 소스
35. 원도우 배치 프로그램 실행하기
36. 메일을 발송하는 프로그램 소스
37. 세션관련 정리 소스
38. 로긴 및 서블릿 관련 소스(한글처리)
39. 쿠키 셋팅에 관한 예제
40. 클래스를 이용하는 샘플예제 소스
41. 버블 소트와 중복체크 예제
42. 날짜 체크하는 메소드 만들기
43. 조건에 맞게 메일을 보내는 소스
44. 로그를 만드는 소스
#####################################################################
44. 로그를 만드는 소스
#####################################################################
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LogMaker{
static SimpleDateFormat simpledateformat = new SimpleDateFormat("HH:mm:ss");
public static void println(String filename, String log){
try{
Date date = new Date();
String pid = simpledateformat.format(date);
//System.out.println("LogMaker String pid->/"+pid+"/");
FileWriter fw = new FileWriter(filename+".log",true);
fw.write(pid + " : "+log+"\n");
fw.flush();
fw.close();
} catch(Exception ex){
}
}
}
#####################################################################
#####################################################################
43. 조건에 맞게 메일을 보내는 소스
#####################################################################
import java.sql.*;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.StringTokenizer;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AirforwarderMailNCC extends Thread
{
public static void main(String[] args) throws MessagingException
{
Connection conn_0 = null;
PreparedStatement pstmt_0 = null;
ResultSet rs_0 = null;
String sDB_URL = "jdbc:oracle:thin:@165.213.251.202:1521:itts";
String sDB_USER = "itts";
String sDB_PASSWORD = "skan00";
String name ="PTS_AirforwarderNCC";
String from = "pts.sec@samsung.com";
String to = null;
String title = "Notice from PTS";
String contents = null;
String host = "203.254.221.26";
String logDir = "log";
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date d = c.getTime();
String fid = simpledateformat.format(d);
File resultFile = new File(logDir, fid);
if(resultFile.exists()== false)
resultFile.mkdir();
logDir = logDir + File.separator + fid;
boolean ok1 = false, ok2 = false, ok3 = false;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
StringBuffer sbSql_0 = new StringBuffer();
sbSql_0.append(" SELECT EMAIL, USER_NAME, USER_ID FROM USER_INFO U, BASIC_CODE B WHERE U.COMPANY_CODE=B.CODE AND DESC2 like 'AIR%' AND U.EMAIL IS NOT NULL AND U.STATUS='approved' AND U.PTS_MAIL='T' AND USER_TYPE='CARRIERLOAD' ");
conn_0 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
pstmt_0 = conn_0.prepareStatement(sbSql_0.toString());
rs_0 = pstmt_0.executeQuery();
int cnt_total = 0;
while(rs_0.next()){
int cnt_new = 0, cnt_change = 0, cnt_cancel = 0;
to = rs_0.getString("EMAIL");
//Count 보낼 메일 가져오기
StringBuffer sbSql_newmail = new StringBuffer(); //New Mail Count
sbSql_newmail.append(" SELECT INV_NO, BILLNO_, UPDDATE, GETCONSIGNAME(CONSIG) CONSIG_NAME, GETCONSIGNAME(SHIPPE) SHIPPE_NAME, TRSTYP, MLDTUE, GI_DAT , A.CREDATE FROM INV_DOC A, USER_INFO U WHERE USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'A' AND A.UPDDATE = '99991231235959' AND MAIL_STS='F' ");
Connection conn_1 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_1 = conn_1.prepareStatement(sbSql_newmail.toString());
pstmt_1.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅
ResultSet rs_1 = pstmt_1.executeQuery();
while(rs_1.next()){
cnt_new = rs_1.getRow();
}
pstmt_1.close();
rs_1.close();
conn_1.close();
StringBuffer sbSql_changemail = new StringBuffer(); //Changed Mail Count
sbSql_changemail.append(" SELECT INV_NO, BILLNO_, UPDDATE, GETCONSIGNAME(CONSIG) CONSIG_NAME, GETCONSIGNAME(SHIPPE) SHIPPE_NAME, TRSTYP, MLDTUE, GI_DAT , A.CREDATE FROM INV_DOC A, USER_INFO U WHERE USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'A' AND A.UPDDATE <> '99991231235959' AND MAIL_STS='F' ");
Connection conn_3 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_3 = conn_3.prepareStatement(sbSql_changemail.toString());
pstmt_3.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅
ResultSet rs_3 = pstmt_3.executeQuery();
while(rs_3.next()){
cnt_change = rs_3.getRow();
}
System.out.println("보낼 Change Content 갯수 "+cnt_change);
pstmt_3.close();
rs_3.close();
conn_3.close();
StringBuffer sbSql_cancelmail = new StringBuffer(); //Canceled Mail Count
sbSql_cancelmail.append(" SELECT INV_NO, BILLNO_, UPDDATE, GETCONSIGNAME(CONSIG) CONSIG_NAME, GETCONSIGNAME(SHIPPE) SHIPPE_NAME, TRSTYP, MLDTUE, GI_DAT , A.CREDATE FROM INV_DOC A, USER_INFO U WHERE USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'D' AND MAIL_STS='F' ");
Connection conn_5 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_5 = conn_5.prepareStatement(sbSql_cancelmail.toString());
pstmt_5.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅
ResultSet rs_5 = pstmt_5.executeQuery();
while(rs_5.next()){
cnt_cancel = rs_5.getRow();
}
System.out.println("보낼 Cancel Content 갯수 "+cnt_cancel);
System.out.println();
pstmt_5.close();
rs_5.close();
conn_5.close();
// End 메일 카운터 RS_0 ~ RS_7
//이쪽에서 한개의 메일을 받아서 아래의 컨텐츠를 보내야 함
StringBuffer sbMessage = new StringBuffer();
sbMessage.append("<html><head>");
sbMessage.append("<style type=\"text/css\" >");
sbMessage.append("BODY,TD,font {");
sbMessage.append("color: #666666; font-family: Arial; font-size:9pt;line-height: 130%;}");
sbMessage.append("A:link {color:#00639C;text-decoration: underline;}");
sbMessage.append("A:visited {color:#006699;text-decoration:underline;}");
sbMessage.append("A:active {color:#006699;text-decoration:none;}");
sbMessage.append("A:hover {color:#FFFFFF;text-decoration:none;background-color:#E4628B;}");
sbMessage.append("</style></head><body>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0>");
sbMessage.append("<tr><td height=4 bgcolor=#CDCDCD><img src=http://www.samsungitts.com/img/ptmail/blank.gif width=1 height=1></td></tr>");
sbMessage.append("<tr><td height=43 bgcolor=#0A79A8><img src=http://www.samsungitts.com/img/ptmail/logo.gif width=127 height=43></td></tr></table>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0>");
sbMessage.append("<tr><td width=551 class=text><Br><br><p>Dear, "+rs_0.getString("USER_ID")+"</p><br><br>");
sbMessage.append("Please, check the documents below.<br>");
sbMessage.append("<b>*Total number of new invoices - <b>"+cnt_new+"</b> cases<br> </b>");
sbMessage.append("<b>*Total number of changed invoices - <b>"+cnt_change+"</b> cases<br> </b>");
sbMessage.append("<b>*Total number of canceled invoices - <b>"+cnt_cancel+"</b> cases<br> </b>");
sbMessage.append("Please check it at <a href=http://www.samsungitts.com target=_blank>http://www.samsungitts.com</a></p> <br></p></td>");
sbMessage.append("<td width=149 valign=top><img src=http://www.samsungitts.com/img/ptmail/img.jpg width=160 height=172></td></tr></table>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td><p><b>New Invoice</b> (You have not opened or printed.)</p></td></tr></table>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td bgcolor=#669900>");
sbMessage.append("<table width=700 border=0 cellspacing=1 cellpadding=0>");
sbMessage.append("<tr align=center bgcolor=#BBDD75>");
sbMessage.append("<td height=20><strong>I/V No.</strong></td>");
sbMessage.append("<td height=20><strong>B/L No.</strong></td>");
sbMessage.append("<td height=20><strong>Consignee</strong></td>");
sbMessage.append("<td height=20><strong>Trans Type</strong></td>");
sbMessage.append("<td height=20><strong>ETA</strong></td>");
sbMessage.append("<td height=20><strong>ETD</strong></td></tr>");
StringBuffer sbSql_1= new StringBuffer(); // New Mail Send
sbSql_1.append(" SELECT INV_NO, BILLNO_, GETCONSIGNAME(CONSIG) CONSIG_NAME, TRSTYP, MLDTUE, GI_DAT FROM INV_DOC A, USER_INFO U WHERE USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'A' AND A.UPDDATE = '99991231235959' AND MAIL_STS='F' ");
Connection conn_9 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_9 = conn_9.prepareStatement(sbSql_1.toString());
pstmt_9.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅
ResultSet rs_9 = pstmt_9.executeQuery();
ok1 = false;
while(rs_9.next()){
ok1 = true;
sbMessage.append("<tr align=center bgcolor=#BBDD75>");
sbMessage.append("<td height=20>"+rs_9.getString("INV_NO")+"</td>");
sbMessage.append("<td height=20>"+rs_9.getString("BILLNO_")+"</td>");
sbMessage.append("<td height=20>"+rs_9.getString("CONSIG_NAME")+"</td>");
sbMessage.append("<td height=20>"+rs_9.getString("TRSTYP")+"</td>");
sbMessage.append("<td height=20>"+rs_9.getString("MLDTUE")+"</td>");
sbMessage.append("<td height=20>"+rs_9.getString("GI_DAT")+"</td>");
sbMessage.append("</tr>");
//Update
StringBuffer sb_update0 = new StringBuffer();
sb_update0.append (" UPDATE INV_DOC SET MAIL_STS='T' WHERE INV_NO=? ");
Connection con_update0 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_update0 = con_update0.prepareStatement(sb_update0.toString());
pstmt_update0.setString(1, rs_9.getString("INV_NO"));
ResultSet rs_update0 = pstmt_update0.executeQuery();
con_update0.commit();
rs_update0.close();
pstmt_update0.close();
con_update0.close();
}// 9 For 문
pstmt_9.close();
rs_9.close();
conn_9.close();
//데이타 없을때 처리
if(!ok1){
sbMessage.append("<tr bgcolor=#ffffff><td colspan=6><center><b>No Data Found</b></center></td></tr>");
}
sbMessage.append("</table></table><br><br>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td><p><b>Changed Invoice</b></p></td></tr></table>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td bgcolor=#669900>");
sbMessage.append("<table width=700 border=0 cellspacing=1 cellpadding=0>");
sbMessage.append("<tr align=center bgcolor=#BBDD75>");
sbMessage.append("<td height=20><strong>I/V No.</strong></td>");
sbMessage.append("<td height=20><strong>B/L No.</strong></td>");
sbMessage.append("<td height=20><strong>Consignee</strong></td>");
sbMessage.append("<td height=20><strong>Trans Type</strong></td>");
sbMessage.append("<td height=20><strong>ETA</strong></td>");
sbMessage.append("<td height=20><strong>ETD</strong></td></tr>");
StringBuffer sbSql_2= new StringBuffer(); //Changed Mail Send
sbSql_2.append(" SELECT INV_NO, BILLNO_, GETCONSIGNAME(CONSIG) CONSIG_NAME, TRSTYP, MLDTUE, GI_DAT FROM INV_DOC A, USER_INFO U WHERE USER_ID=? AND SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'A' AND A.UPDDATE <> '99991231235959' AND MAIL_STS='F' ");
Connection conn_10 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_10 = conn_10.prepareStatement(sbSql_2.toString());
pstmt_10.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅
ResultSet rs_10 = pstmt_10.executeQuery();
ok2 = false ;
while(rs_10.next()){
ok2 = true;
sbMessage.append("<tr align=center bgcolor=#BBDD75>");
sbMessage.append("<td height=20>"+rs_10.getString("INV_NO")+"</td>");
sbMessage.append("<td height=20>"+rs_10.getString("BILLNO_")+"</td>");
sbMessage.append("<td height=20>"+rs_10.getString("CONSIG_NAME")+"</td>");
sbMessage.append("<td height=20>"+rs_10.getString("TRSTYP")+"</td>");
sbMessage.append("<td height=20>"+rs_10.getString("MLDTUE")+"</td>");
sbMessage.append("<td height=20>"+rs_10.getString("GI_DAT")+"</td>");
sbMessage.append("</tr>");
//Do Update
System.out.println("Change Invoice Number :::: "+rs_10.getString("INV_NO"));
StringBuffer sb_update1 = new StringBuffer();
sb_update1.append (" UPDATE INV_DOC SET MAIL_STS='T' WHERE INV_NO=? ");
Connection con_update1 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_update1 = con_update1.prepareStatement(sb_update1.toString());
pstmt_update1.setString(1, rs_10.getString("INV_NO"));
ResultSet rs_update1 = pstmt_update1.executeQuery();
con_update1.commit();
rs_update1.close();
pstmt_update1.close();
con_update1.close();
} // 10 For 문
pstmt_10.close();
rs_10.close();
conn_10.close();
if(!ok2){
sbMessage.append("<tr bgcolor=#ffffff><td colspan=6><center><b>No Data Found</b></center></td></tr>");
}
sbMessage.append("</table></table><br><br>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td><p><b>Canceled Invoice</b> (The shipper has canceled.)</p></td></tr></table>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0><tr><td bgcolor=#669900>");
sbMessage.append("<table width=700 border=0 cellspacing=1 cellpadding=0>");
sbMessage.append("<tr align=center bgcolor=#BBDD75>");
sbMessage.append("<td height=20><strong>I/V No.</strong></td>");
sbMessage.append("<td height=20><strong>B/L No.</strong></td>");
sbMessage.append("<td height=20><strong>Consignee</strong></td>");
sbMessage.append("<td height=20><strong>Trans Type</strong></td>");
sbMessage.append("<td height=20><strong>ETA</strong></td>");
sbMessage.append("<td height=20><strong>ETD</strong></td></tr>");
StringBuffer sbSql_3= new StringBuffer(); //Canceled Mail Send
sbSql_3.append(" SELECT INV_NO, BILLNO_, GETCONSIGNAME(CONSIG) CONSIG_NAME, TRSTYP, MLDTUE, GI_DAT FROM INV_DOC A, USER_INFO U WHERE SHIPPE <> 'C100' AND A.SHIPPE = U.DEALING_SUBSIDIARY_CODE AND A.MLCARI = U.COMPANY_CODE AND MLCARI <> 'SITA' AND SHIPPE <> 'C100' AND TRSTYP = 'AIR' AND A.RCDFLG = 'D' AND MAIL_STS='F' AND USER_ID=? ");
Connection conn_11 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_11 = conn_11.prepareStatement(sbSql_3.toString());
pstmt_11.setString(1, rs_0.getString("USER_ID")); //순차적으로 조건을 셋팅
ResultSet rs_11 = pstmt_11.executeQuery();
ok3 = false ;
while(rs_11.next()){
ok3 = true;
sbMessage.append("<tr align=center bgcolor=#BBDD75>");
sbMessage.append("<td height=20>"+rs_11.getString("INV_NO")+"</td>");
sbMessage.append("<td height=20>"+rs_11.getString("BILLNO_")+"</td>");
sbMessage.append("<td height=20>"+rs_11.getString("CONSIG_NAME")+"</td>");
sbMessage.append("<td height=20>"+rs_11.getString("TRSTYP")+"</td>");
sbMessage.append("<td height=20>"+rs_11.getString("MLDTUE")+"</td>");
sbMessage.append("<td height=20>"+rs_11.getString("GI_DAT")+"</td>");
sbMessage.append("</tr>");
//Do Update
StringBuffer sb_update2 = new StringBuffer();
sb_update2.append (" UPDATE INV_DOC SET MAIL_STS='T' WHERE INV_NO=? ");
Connection con_update2 = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
PreparedStatement pstmt_update2 = con_update2.prepareStatement(sb_update2.toString());
pstmt_update2.setString(1, rs_11.getString("INV_NO"));
ResultSet rs_update2 = pstmt_update2.executeQuery();
con_update2.commit();
rs_update2.close();
pstmt_update2.close();
con_update2.close();
} // 11 For 문
pstmt_11.close();
rs_11.close();
conn_11.close();
if(!ok3){
sbMessage.append("<tr bgcolor=#ffffff><td colspan=6><center><b>No Data Found</b></center></td></tr>");
}
sbMessage.append("</table></table><br><br>");
sbMessage.append("</table></table><br></td></tr></table><br>");
sbMessage.append("<table width=700 border=0 cellspacing=0 cellpadding=0>");
sbMessage.append("<tr><td height=1 bgcolor=#CDCDCD><img src=http://www.samsungitts.com/img/ptmail/blank.gif width=1 height=1></td> </tr>");
sbMessage.append("<tr><td align=center>Copyright(c)2003 Samsung Electronics co.,Ltd. All rights reserved.</td></tr></table> </body></html>");
contents = sbMessage.toString();
//System.out.println("내용 확인 222222222222 "+contents);
if(ok1 || ok2 || ok3){
StringTokenizer stTo = new StringTokenizer(to, ";");
while(stTo.hasMoreTokens()){
to = stTo.nextToken();
//메일 클래스 객체 생성
Properties prop = System.getProperties();
Session session = Session.getInstance(prop, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(name+"<"+from+">"));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(title);
message.setContent(contents,"text/html;charset=euc-kr");
//message.setText(contents);
Transport transport = session.getTransport("smtp");
transport.connect(host,"","");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
LogMaker lm = new LogMaker();
lm.println(logDir+File.separator+"AirforwarderMailNCC", to);
}
++cnt_total;
System.out.println("Total Mail 갯수 "+cnt_total);
}else{
System.out.println("메일을 보내지 않는다");
System.out.println();
}
} //Mail For 문
Thread.currentThread().sleep(50);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(pstmt_0 != null){pstmt_0.close();}
if(rs_0 != null){rs_0.close();}
if(conn_0 != null){conn_0.close();}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
#####################################################################
#####################################################################
42. 날짜 체크하는 메소드 만들기
#####################################################################
import java.util.*;
import java.text.*;
public class DateTest
{
public String checkDate(String input){
String reVal = null;
//리턴 타입을 설정한다
try
{
if ( input == null || input.length() != 8 )
{
return input;
//OR의 우선순위는 앞에 있슴. 에러사항을 체크하여 Return을 한다
}
Calendar cl = Calendar.getInstance();
int yyyy = Integer.parseInt(input.substring(0, 4));
int month = Integer.parseInt(input.substring(4, 6));
int day = Integer.parseInt(input.substring(6));
//입력값에 대해서 substring으로 나누어 가져온다
cl.set(yyyy, month-1, day);
//Calendar에 년월일을 셋팅한다
/*
int yy = cl.get(Calendar.YEAR);
int mm = cl.get(Calendar.MONTH)+1;
int dd = cl.get(Calendar.DATE);
System.out.println(yy +", "+mm+", "+dd);
*/
String date_format = "yyyyMMdd";
SimpleDateFormat simpledateformat = new SimpleDateFormat(date_format);
reVal = simpledateformat.format(cl.getTime());
}catch (Exception e)
{
e.printStackTrace();
return input;
}
return reVal;
//try catch 구분 밖에서 Return 타입을 받는다
}
public static void main(String[] args)
{
DateTest dt = new DateTest();
System.out.println( dt.checkDate("20050200") );
//객체를 생성하여 메소드를 호출한다
}
}
#####################################################################
41. 버블 소트와 중복체크 예제
#####################################################################
import java.util.*;
public class RandomTest
{
public static void main(String[] args)
{
Random random = new Random();
boolean[] boo = new boolean[45];
int[] choo = new int[6];
for (int i=0; i<boo.length ; )
{
boo[i] = true;
}
for (int i=0; i<choo.length ; i++)
{
int num = random.nextInt(45);
if (boo[num])
{
boo[num] = false;
choo[i] = num+1;
}
System.out.println(choo[i]);
}
}
}
class SortTest
{
public static void main(String[] args)
{
String[] str = {"Orange","Apple","Grape","Peach","Lemon"};
System.out.println("@@@@@ 정렬 전 @@@@@");
for (int i=0; i<str.length; i++)
{
System.out.println(str[i]);
}
System.out.println("@@@@@ 정렬 후 @@@@@");
for (int j=0; j<str.length ; j++ )
{
for (int i= j+1 ; i<str.length ; i++)
{
if ( str[i].compareTo(str[j]) < 0 )
{
String temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
System.out.println(str[j]);
}
}
}
#####################################################################
#####################################################################
40. 클래스를 이용하는 샘플예제 소스
#####################################################################
class TopScret
{
private int scret;
public void setScret(int x){
scret = x;
}
public int getScret(){
return scret;
}
}
public class TopScretMain
{
public static void main(String[] args){
TopScret top = new TopScret();
top.setScret(4000);
int i = top.getScret();
System.out.println("i ->"+i);
System.out.println("top.getScret() ->"+top.getScret());
}
};
class MeanCalc
{
private int sum;
private int num;
public void setValue(int x, int y, int z, int n){
sum = x * y * z;
num = n;
}
public int getValue(){
return sum - num;
}
}
public class MeanCalcMain
{
public static void main(String[] args){
MeanCalc cal = new MeanCalc();
cal.setValue(100, 40, 500, 6);
int z = cal.getValue();
System.out.println("z ->"+z);
System.out.println("cal ->"+cal);
}
};
class MotorCycle
{
private int id;
private int speed;
public void setData(int x, int y){
id = x;
speed = y;
}
public void drive(){
System.out.println("id ->"+id);
System.out.println("speed ->"+speed);
}
}
public class MotorCycleMain
{
public static void main(String[] args){
MotorCycle m = new MotorCycle();
m.setData(5384, 120);
m.drive();
System.out.println("m ->"+m);
MotorCycle c = m;
c.setData(7777, 100);
c.drive();
System.out.println("c ->"+c);
}
};
#####################################################################
#####################################################################
39. 쿠키 셋팅에 관한 예제
#####################################################################
<form method="post" action="setCookie.jsp">
<input type="text" name="id"><br>
<input type="password" name="passwd"><br>
<input type="submit"><input type="reset">
<%@ page contentType="text/html;charset=euc-kr"%>
<%
String id = request.getParameter("id");
String passwd = request.getParameter("passwd");
String value = request.getHeader("Cookie");
if (value == null){
Cookie cookie = new Cookie(id, passwd);
cookie.setMaxAge(60);
response.addCookie(cookie);
out.println("Setting Cookie<br><hr>");
out.println("id :"+id+ "<br>passwd :"+passwd);
}else{
out.println("Have done Cookie<br><hr>");
out.println("id :"+id+ "<br>passwd :"+passwd+"<br>");
Cookie[] cookies = request.getCookies();
for (int i=0; i<cookies.length; i++){
out.println("name :"+cookies[i].getName()+"<br>");
out.println("value :"+cookies[i].getValue()+"<br>");
out.println("domain :"+cookies[i].getDomain()+"<br>");
out.println("maxage :"+cookies[i].getMaxAge()+"<br>");
out.println("path :"+cookies[i].getPath()+"<br>");
out.println("secure :"+cookies[i].getSecure()+"<br>");
out.println("comment :"+cookies[i].getComment()+"<br>");
out.println("version :"+cookies[i].getVersion()+"<br>");
}
}
%>
#####################################################################
#####################################################################
38. 로긴 및 서블릿 관련 소스(한글처리)
#####################################################################
<BODY onContextmenu="return false">
<form name="login" action="/ServletJsp/servlet/loginServlet" method="post">
<table border=1 cellspacing="0" cellpadding="0">
<tr>
<td>User ID </td>
<td><input type="text" name="id" ></td>
</tr>
<tr>
<td>Password </td>
<td><input type="password" name="passwd"></td>
</tr>
<tr>
<td colspan=2 align=center>
<input type="submit" value="CONFIRM">
<input type="reset" value="CANCEL">
</td>
</tr>
</table>
</form>
</BODY>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import util.HangulConversion;
public class loginServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
//res.setContentType("text/html;charset=euc-kr");// 필히 설정함
//PrintWriter out = res.getWriter();
res.setContentType("text/html");
PrintWriter out = new PrintWriter( new OutputStreamWriter(res.getOutputStream(), "KSC5601"), true );
String userid = HangulConversion.toKor(req.getParameter("id")); //util 팩키지에서 메소드 이용
String passwd = req.getParameter("passwd");
out.println("<html><body>");
if ( userid.equals("") && passwd.equals(""))
{
out.println("NOWHERE");
}else{
out.println("INPUT ID IS :"+ userid +"<br>");
out.println("INPUT PASSWORD IS :"+passwd);
}
out.println("<p><font size=2><a href=javascript:history.back()>BACK TO THE FUTURE</a></font>");
out.println("<body></html>");
out.close();
}
}
package util;
import java.io.*;
public class HangulConversion
{
public static String toEng(String ko){
if (ko ==null)
{
return null;
}
try
{
return new String(ko.getBytes("KSC5601"), "8859_1");
}
catch (Exception e)
{
return ko;
}
}
public static String toKor(String en){
if (en == null)
{
return null;
}
try
{
return new String(en.getBytes("8859_1"), "KSC5601");
}
catch (Exception e)
{
return en;
}
}
}
#####################################################################
37. 세션관련 정리 소스
#####################################################################
<form action="sessionCreate.jsp" method="post">
<table border="1" cellspacing=0 cellpadding=0 >
<tr>
<td> IDENTIFICATION </td>
<td><input type=textfield name=id></td>
</tr>
<tr align=center>
<td colspan=2><input type="submit" value="Confirm"><input type="reset" value="Cancel"></td>
</tr>
<table>
</form>
<%@ page contentType="text/html;charset=euc-kr" session="false"%>
<%@ page import="util.HangulConversion"%>
<html>
<body>
Session Creation<br>
<%
String id = HangulConversion.toKor(request.getParameter("id"));
if (id.equals("")){
out.println("<hr>No Data<br>");
out.println("<a href=javascript:history.back()>Back To The Future</a>");
//response.sendRedirect("sessionLogin.html");
return;
}
HttpSession session = request.getSession(true);
if(session.isNew()){
session.setAttribute("id", id); //세션을 설정한다
out.println("<hr>New session is created :"+ id+"<br>");
out.println("Session ID :"+session.getId()+"<br>");
out.println("<a href=sessionRead.jsp>[Get Session]</a><br>");
}else{
out.println("<hr>Already exist session<br>");
out.println("Input Id :"+id +"<br>");
out.println("Session ID :"+session.getId()+"<br>"); //기존에 만든 세선 Id를 가져온다
out.println("<a href=sessionRead.jsp>[Get Session]</a>");
}
%>
</body>
</html>
<%@ page contentType="text/html;charset=euc-kr" session="false"%>
<html>
<body>
<%
HttpSession session = request.getSession(false);
String s = (String)session.getAttribute("id");
if (s == null){
out.println("Not Session");
}else{
out.println("Attribute id is :"+s+"<br>");
}
%>
<hr>
isNew() :<%= session.isNew()%><br>
Session ID :<%= session.getId()%><br>
Session Create Time :<%= new java.util.Date(session.getCreationTime()).toString()%><br>
Session Last Time :<%= new java.util.Date(session.getLastAccessedTime()).toString()%><br>
Session Active Time :<%= session.getMaxInactiveInterval()%> sec<br>
<a href="sessionDelete.jsp">[Session Delete]</a> <a href="sessionLogin.html">[Login Page]</a>
</body>
</html>
<%@ page contentType="text/html;charset=euc-kr" session="false" %>
<%
HttpSession session = request.getSession(false);
String s = (String)session.getAttribute("id");
out.println("Id :"+s+"<br><hr>");
if (session != null){
session.invalidate();
}
%>
Delete Session<br>
<a href="sessionLogin.html">Login Page</a>
#####################################################################
36. 메일을 발송하는 프로그램 소스
#####################################################################
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
/**
* @param pMAIL
* @param conn
*/
public Properties sendCronMail(Properties pARGS, Connection conn) {
Properties pRETURN = new Properties();
pRETURN.setProperty("RESULT", "true");
String sMAIL_SMTP_HOST = pARGS.getProperty("MAIL_SMTP_HOST", "203.254.221.26");
String sEMAIL_ADDRESS_FROM = pARGS.getProperty("EMAIL_ADDRESS_FROM", "swbupload@samsung.com"); // 보내는 사람 주소
String sEMAIL_ADDRESS_TO = pARGS.getProperty("EMAIL_ADDRESS_TO", "swbupload@samsung.com"); // 받는 사람 주소
String sSUBJECT = pARGS.getProperty("SUBJECT", "CronMail Error..."); // 타이틀
String sTEXT = pARGS.getProperty("TEXT", "CronMail Error!!!"); // 내용
try {
Properties pMAIL = System.getProperties();
pMAIL.put("mail.smtp.host", sMAIL_SMTP_HOST);
Session sMAIL_SESSION = Session.getDefaultInstance(pMAIL, null);
if (sMAIL_SESSION == null) {
pRETURN.setProperty("RESULT", "false");
pRETURN.setProperty("MSG", "Mail Session can't be created...");
return pRETURN;
}
MimeMessage reply = new MimeMessage(sMAIL_SESSION);
reply.setFrom(new InternetAddress(sEMAIL_ADDRESS_FROM));
reply.setSubject(sSUBJECT);
reply.setText(sTEXT);
reply.addRecipient(Message.RecipientType.TO, new InternetAddress(sEMAIL_ADDRESS_TO));
Transport.send(reply);
StringBuffer sbSQL = new StringBuffer();
sbSQL.append(" UPDATE SENDMAIL SET SENDDATE = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') WHERE MAIL_ID = ?");
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement(sbSQL.toString());
pstmt.setString(1, pARGS.getProperty("MAIL_ID", "1"));
pstmt.executeUpdate();
conn.commit();
} catch (Exception e) {
pRETURN.setProperty("RESULT", "false");
pRETURN.setProperty("MSG", "sendCronMail(Properties pARGS) Error : " + e.toString());
}
return pRETURN;
}
public static void main(String[] args) {
String sDB_URL = "jdbc:oracle:thin:@165.213.251.202:1521:itts";
String sDB_USER = "itts";
String sDB_PASSWORD = "skan00";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(sDB_URL, sDB_USER, sDB_PASSWORD);
if (conn != null) {
StringBuffer sbSQL = new StringBuffer();
sbSQL.append(" SELECT MAIL_ID, MAIL_FROM, MAIL_TO, MAIL_SUBJECT, MAIL_BODY FROM SENDMAIL WHERE SENDDATE = '99991231235959'");
pstmt = conn.prepareStatement(sbSQL.toString());
rs = pstmt.executeQuery();
Hashtable htSENDMAIL = new Hashtable();
for (int i = 0; rs.next(); i++) {
Properties pSendCronMail_ARGS = new Properties();
pSendCronMail_ARGS.setProperty("MAIL_ID", rs.getString("MAIL_ID"));
pSendCronMail_ARGS.setProperty("EMAIL_ADDRESS_FROM", rs.getString("MAIL_FROM"));
pSendCronMail_ARGS.setProperty("EMAIL_ADDRESS_TO", rs.getString("MAIL_TO"));
pSendCronMail_ARGS.setProperty("SUBJECT", rs.getString("MAIL_SUBJECT"));
pSendCronMail_ARGS.setProperty("TEXT", rs.getString("MAIL_BODY"));
htSENDMAIL.put(new Integer(i), pSendCronMail_ARGS);
}
rs.close();
pstmt.close();
SendMail cm = new SendMail();
for (int i = 0; i < htSENDMAIL.size(); i++) {
cm.sendCronMail((Properties) htSENDMAIL.get(new Integer(i)), conn);
}
}
} catch (ClassNotFoundException e) {
System.err.println(e.toString());
} catch (SQLException e) {
System.err.println(e.toString());
} finally {
try {
conn.close();
} catch (SQLException e1) {
System.err.println(e1.toString());
}
}
}
}
#####################################################################
35. 원도우 배치 프로그램 실행하기
#####################################################################
xcopy /s /e /y C:\Tomcat4\webapps\itts\paperless\fileupload e:\paperless\fileupload
move /Y C:\Tomcat4\webapps\itts\paperless\swbTempDir\*.* D:\PT-LOG\swbTempDir\
move /Y C:\Tomcat4\webapps\itts\paperless\mProSystem\log\*.* D:\PT-LOG\mProSystem\
move /Y C:\Tomcat4\webapps\itts\paperless\logs\*.* D:\PT-LOG\logs\
#####################################################################
34. 특정 폴더에 쌓이는 파일을 없애는 소스
#####################################################################
배치 프로그램을 돌리면서 로그파일을 남김.
java paperless.cron.TempPdfDelete e:\\pdf_temp 1 >> PtPDF_TEMP_DIR_DEL.log
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class TempPdfDelete {
public static void main(String[] args) {
TempPdfDelete td = new TempPdfDelete();
String sTRASH_LOCATION = "e:\\pdf_temp";
String sTRASH_DELETE_DAY = "1";
if( args.length == 2 ) {
sTRASH_LOCATION = args[0];
sTRASH_DELETE_DAY = args[1];
}
Properties pARGS = new Properties();
pARGS.setProperty("TRASH_LOCATION", sTRASH_LOCATION);
pARGS.setProperty("TRASH_DELETE_DAY", sTRASH_DELETE_DAY);
Properties pRETURN = td.trashDelete(pARGS);
SimpleDateFormat sdfTODAY = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dTODAY = new Date();
System.out.println("[" + sdfTODAY.format(dTODAY) + "] '"+sTRASH_LOCATION+"' Directory Deletion Started...");
for(int i=0; i<Integer.parseInt(pRETURN.getProperty("DELETED_TRASH_FILE_COUNT")); i++) {
dTODAY = new Date();
System.out.println("[" + sdfTODAY.format(dTODAY) + "] " + pRETURN.getProperty("#" + i, "Deleted File Name not found") + " was deleted");
}
dTODAY = new Date();
System.out.println("[" + sdfTODAY.format(dTODAY) + "] '"+sTRASH_LOCATION+"' Directory Deletion Ended...");
}
/**
* @param pARGS
* @return
*/
private Properties trashDelete(Properties pARGS) {
Properties pRETURN = new Properties();
pRETURN.setProperty("RESULT", "true");
String sTRASH_LOCATION = pARGS.getProperty("TRASH_LOCATION", "e:\\pdf_temp");
if (sTRASH_LOCATION.trim().equals("")) {
pRETURN.setProperty("RESULT", "true");
pRETURN.setProperty("MSG", "TRASH_LOCATION is null...");
return pRETURN;
}
long lTRASH_DELETE_DAY = Long.parseLong(pARGS.getProperty("TRASH_DELETE_DAY", "0")) * 24 * 60 * 60 * 1000;
File fTRASH_LOCATION = new File(sTRASH_LOCATION);
int iDELETED_TRASH_FILE_COUNT = 0;
if (fTRASH_LOCATION.isDirectory()) {
File[] fofTRASH_LOCATION_FILES = fTRASH_LOCATION.listFiles();
Date dTODAY = new Date();
for (int i = 0; i < fofTRASH_LOCATION_FILES.length; i++) {
long lTRASH_FILE_AGE = dTODAY.getTime() - fofTRASH_LOCATION_FILES[i].lastModified();
if (fofTRASH_LOCATION_FILES[i].isFile() && lTRASH_FILE_AGE >= lTRASH_DELETE_DAY) {
if (fofTRASH_LOCATION_FILES[i].delete()) {
pRETURN.setProperty("#" + String.valueOf(iDELETED_TRASH_FILE_COUNT), fofTRASH_LOCATION_FILES[i].getName());
iDELETED_TRASH_FILE_COUNT++;
}
}
}
}
pRETURN.setProperty("DELETED_TRASH_FILE_COUNT", String.valueOf(iDELETED_TRASH_FILE_COUNT));
return pRETURN;
}
}
#####################################################################
33. 암호와 알고리즘을 사용후 복호화 하는 소스와 적용예
#####################################################################
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AlgoDES {
static byte[] seedKeyData = new byte[24];
public AlgoDES() {
seedKeyData[0] = 0x01;
seedKeyData[1] = 0x02;
seedKeyData[2] = 0x03;
seedKeyData[3] = 0x04;
seedKeyData[4] = 0x05;
seedKeyData[5] = 0x06;
seedKeyData[6] = 0x07;
seedKeyData[7] = 0x08;
seedKeyData[8] = 0x09;
seedKeyData[9] = 0x10;
seedKeyData[10] = 0x11;
seedKeyData[11] = 0x12;
seedKeyData[12] = 0x13;
seedKeyData[13] = 0x14;
seedKeyData[14] = 0x15;
seedKeyData[15] = 0x16;
seedKeyData[16] = 0x01;
seedKeyData[17] = 0x02;
seedKeyData[18] = 0x03;
seedKeyData[19] = 0x04;
seedKeyData[20] = 0x05;
seedKeyData[21] = 0x06;
seedKeyData[22] = 0x07;
seedKeyData[23] = 0x08;
}
public static String encTripleDES(String beforeStr) {
String afterStr = "";
try {
SecretKeySpec desKey = new SecretKeySpec(seedKeyData, "DESede"); //seedKeyData로 암호화
Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
byte[] cleartext = beforeStr.getBytes();
desCipher.init(Cipher.ENCRYPT_MODE, desKey);
byte[] ciphertext = desCipher.doFinal(cleartext);
afterStr = (new BASE64Encoder()).encode(ciphertext);
} catch (Exception e) {
e.printStackTrace();
}
return afterStr;
}
public static String decTripleDES(String beforeStr) {
String afterStr = "";
try {
SecretKeySpec desKeyD = new SecretKeySpec(seedKeyData, "DESede");
Cipher desCipherD = Cipher.getInstance("DESede/ECB/PKCS5Padding");
desCipherD.init(Cipher.DECRYPT_MODE, desKeyD);
byte[] decodedBytes = (new BASE64Decoder()).decodeBuffer(beforeStr);
byte[] cleartext1 = desCipherD.doFinal(decodedBytes);
afterStr = new String(cleartext1);
} catch (Exception e) {
e.printStackTrace();
}
return afterStr;
}
public static void main(String args[]) {
try{
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
String s = AlgoDES.encTripleDES(args[i]);
String s1 = AlgoDES.decTripleDES(s);
System.out.println("Original ["+args[i]+"]");
System.out.println("encTripleDES ["+s+"]");
System.out.println("decTripleDES ["+s1+"]");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** 적용예제
if(secu) {
_sdbServer = AlgoDES.decTripleDES(ReadConfig.get ("DATABASE", "dbServer")) ;
}else{
_sdbServer = ReadConfig.get ("DATABASE", "dbServer") ;
}
if(secu){
_sdbPassword = AlgoDES.decTripleDES(ReadConfig.get ("DATABASE", "dbPassword")) ;
}else{
_sdbPassword = ReadConfig.get ("DATABASE", "dbPassword") ;
}
*/
#####################################################################
32. 특수문자 제거 메소드
#####################################################################
public static String removeSpecialChar(String str) {
if (str == null || str.trim().length() == 0)
return "";
StringBuffer data = new StringBuffer(str);
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length(); i++) {
char c = data.charAt(i);
if (((int) c > 47 && (int) c < 58) || ((int) c > 64 && (int) c < 91) || ((int) c > 96 && (int) c < 123))
buf.append(c);
}
return buf.toString();
}
#####################################################################
31. 날짜 관련 함수 이용
#####################################################################
import java.util.*;
import java.io.*;
import java.text.*;
public class DateCheck
{
public static void main(String[] args)
{
SimpleDateFormat date = new SimpleDateFormat();
date = (SimpleDateFormat)DateFormat.getDateTimeInstance();
long now = System.currentTimeMillis();
System.out.println("Now ->/"+now+"/");
Date dd = new Date();
System.out.println("Date ->/"+dd+"/");
String str = date.format(new Date(now));
System.out.println("Time ->/"+str+"/");
}
}
#####################################################################
30. Random 함수로 받은 값을 중복 체크하는 소소
#####################################################################
import java.util.*;
public class RandomTest
{
public static void main(String[] args)
{
Random random = new Random();
boolean[] total = new boolean[45];
int[] choose = new int[6];
for (int i=0; i<total.length ; i++ )
{
total[i] = true;
}
for (int i=0; i<choose.length ; i++)
{
int num = random.nextInt(45);
if (total[num])
{
total[num] = false;
choose[i] = num+1;
}
System.out.print( choose[i] + " \n");
}
}
}
#####################################################################
29. 버블 소트로 데이타 정렬
#####################################################################
public class SortTest
{
public static void main(String[] args)
{
String[] str = {"Orange","Apple","Grape","Peach","Lemon"};
System.out.println("@@@@@ 정렬 전 @@@@@");
for (int i=0; i<str.length; i++)
{
System.out.println(str[i]);
}
System.out.println("@@@@@ 정렬 후 @@@@@");
for (int j=0; j<str.length ; j++ )
{
for (int i= j+1 ; i<str.length ; i++)
{
if ( str[i].compareTo(str[j]) < 0 ) //음수이면 들어감
{
String temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
System.out.println(str[j]);
}
}
}
#####################################################################
28. MD5로 암호화 하는 알고리즘 (Base64 필요)
#####################################################################
import sun.misc.*;
import java.io.*;
public class Base64Util {
public Base64Util() {}
/**
* Base64Encoding을 수행한다. binany in ascii out
*
* @param encodeBytes encoding할 byte array
* @return encoding 된 String
*/
public static String encode(byte[] encodeBytes) {
BASE64Encoder base64Encoder = new BASE64Encoder();
ByteArrayInputStream bin = new ByteArrayInputStream(encodeBytes);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = null;
try{
base64Encoder.encodeBuffer(bin, bout);
} catch(Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
buf = bout.toByteArray();
return new String(buf).trim();
}
/**
* Base64Decoding 수행한다. binany out ascii in
*
* @param strDecode decoding할 String
* @return decoding 된 byte array
*/
public static byte[] decode(String strDecode) {
BASE64Decoder base64Decoder = new BASE64Decoder();
ByteArrayInputStream bin = new ByteArrayInputStream(strDecode.getBytes());
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = null;
try {
base64Decoder.decodeBuffer(bin, bout);
} catch(Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
buf = bout.toByteArray();
return buf;
}
}
import java.security.*;
public class SecurityUtil {
/**
* byte[] ret = HashUtil.digest("MD5", "abcd".getBytes());
* 처럼 호출
*/
public static byte[] digest(String alg, byte[] input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(alg);
return md.digest(input);
}
public static String getCryptoMD5String(String inputValue) throws Exception {
if( inputValue == null ) throw new Exception("Can't conver to Message Digest 5 String value!!");
byte[] ret = digest("MD5", inputValue.getBytes());
String result = Base64Util.encode(ret);
return result;
}
public static void main(String[] args) throws Exception
{
String passwd = SecurityUtil.getCryptoMD5String("gkskfh2005");
System.out.println("passwd :"+passwd);
}
}
#####################################################################
#####################################################################
27. TripleDES 을 이용한 암호화 알고리즘
#####################################################################
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AlgoDES {
static byte[] seedKeyData = new byte[24];
public AlgoDES() {
seedKeyData[0] = 0x01;
seedKeyData[1] = 0x02;
seedKeyData[2] = 0x03;
seedKeyData[3] = 0x04;
seedKeyData[4] = 0x05;
seedKeyData[5] = 0x06;
seedKeyData[6] = 0x07;
seedKeyData[7] = 0x08;
seedKeyData[8] = 0x09;
seedKeyData[9] = 0x10;
seedKeyData[10] = 0x11;
seedKeyData[11] = 0x12;
seedKeyData[12] = 0x13;
seedKeyData[13] = 0x14;
seedKeyData[14] = 0x15;
seedKeyData[15] = 0x16;
seedKeyData[16] = 0x01;
seedKeyData[17] = 0x02;
seedKeyData[18] = 0x03;
seedKeyData[19] = 0x04;
seedKeyData[20] = 0x05;
seedKeyData[21] = 0x06;
seedKeyData[22] = 0x07;
seedKeyData[23] = 0x08;
}
public static String encTripleDES(String beforeStr) {
String afterStr = "";
try {
SecretKeySpec desKey = new SecretKeySpec(seedKeyData, "DESede"); //seedKeyData로 암호화
Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
byte[] cleartext = beforeStr.getBytes();
desCipher.init(Cipher.ENCRYPT_MODE, desKey);
byte[] ciphertext = desCipher.doFinal(cleartext);
afterStr = (new BASE64Encoder()).encode(ciphertext);
} catch (Exception e) {
e.printStackTrace();
}
return afterStr;
}
public static String decTripleDES(String beforeStr) {
String afterStr = "";
try {
SecretKeySpec desKeyD = new SecretKeySpec(seedKeyData, "DESede");
Cipher desCipherD = Cipher.getInstance("DESede/ECB/PKCS5Padding");
desCipherD.init(Cipher.DECRYPT_MODE, desKeyD);
byte[] decodedBytes = (new BASE64Decoder()).decodeBuffer(beforeStr);
byte[] cleartext1 = desCipherD.doFinal(decodedBytes);
afterStr = new String(cleartext1);
} catch (Exception e) {
e.printStackTrace();
}
return afterStr;
}
public static void main(String args[]) {
try{
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
String s = AlgoDES.encTripleDES(args[i]);
String s1 = AlgoDES.decTripleDES(s);
System.out.println("Original ["+args[i]+"]");
System.out.println("encTripleDES ["+s+"]");
System.out.println("decTripleDES ["+s1+"]");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.security.*;
import javax.crypto.*;
public class TripleDes {
public static void main(String [] args) throws Exception {
if( args.length != 1) {
System.out.println("Usage : java SimpleExample text ");
System.exit(1);
}
String text = args[0];
System.out.println("Generating a DESded (TripleDES) key...");
// Triple DES 생성
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
keyGenerator.init(168); // 키의 크기를 168비트로 초기화
Key key = keyGenerator.generateKey();
System.out.println("키생성이 완료되었음");
// Cipher를 생성, 사용할 키로 초기화
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte [] plainText = text.getBytes("UTF8");
System.out.println("Plain Text : ");
for (int i = 0; i < plainText.length ; i++) {
System.out.print(plainText[i] + " ");
}
// 암호화 시작
byte [] cipherText = cipher.doFinal(plainText);
// 암호문서 출력
System.out.println("\nCipher Text : ");
for (int i = 0; i < cipherText.length ; i++) {
System.out.print(cipherText[i] + " ");
}
//복호화 모드로서 다시 초기화
cipher.init(Cipher.DECRYPT_MODE, key);
//복호화 수행
byte [] decryptedText = cipher.doFinal(cipherText);
String output = new String(decryptedText, "UTF8");
System.out.println("\nDecrypted Text : " + output);
}
};
#####################################################################
#####################################################################
26. Random 클래스로 가져온 값을 중복체크하기
#####################################################################
import java.util.*;
public class RandomTest
{
public static void main(String[] args)
{
Random random = new Random();
boolean[] boo = new boolean[45];
int[] choo = new int[6];
for (int i=0; i<boo.length ; )
{
boo[i] = true;
}
for (int i=0; i<choo.length ; i++)
{
int num = random.nextInt(45);
if (boo[num])
{
boo[num] = false;
choo[i] = num+1;
System.out.println(choo[i]);
}
}
}
}
#####################################################################
#####################################################################
26. MS-SQL JDBC 드라이버 연결하는 방법
#####################################################################
다음의 사이트를 방문하여 MS-SQL2000용 JDBC 드라이버를 다운로드
http://www.microsoft.com/sql/downloads/2000/jdbc.asp
적절한 위치에 설치하고 다음의 세 파일을 클래스패스에 추가 (%JAVA_HOME%\lib\ext\classes12.zip;)
설치 디렉터리/lib/msbase.jar
설치 디렉터리/lib/msutil.jar
설치 디렉터리/lib/mssqlserver.jar
MS-SQL2000, Oracle 그리고 MySQL 데이터베이스의 드라이버를 로딩하는 것을 각각 보여주고 있습니다.
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("org.gjt.mm.mysql.Driver");
#####################################################################
#####################################################################
25. 날짜 포맷 바꾸는 방법
#####################################################################
String ETA_END_DATE = null;
String ETA_START_DATE = null;
String date_format = "yyyy-MM-dd";
SimpleDateFormat simpledateformat = new SimpleDateFormat(date_format);
ETA_END_DATE = simpledateformat.format(Format.getSwbEndDate());
ETA_START_DATE = simpledateformat.format(Format.getSwbStartDate());
#####################################################################
24. 엔터키를 두르면 검색하는 소스
#####################################################################
<script language="JavaScript">
function goUrl(command, _url) {
theForm = document.searchForm;
if (command == 'search' && theForm.BLNO.value != null)
theForm.BLNO.value = theForm.BLNO.value.toUpperCase();
theForm.command.value=command;
theForm.PAGE.value="1";
theForm.action = _url;
theForm.submit();
}
function EnterCheck()
{
if(event.keyCode == 13)
goUrl('search', '/servlet/paperless.SwbListServlet');
}
</script>
<form name="searchForm" method="post" action="">
<table width="98%" border="0" cellspacing="1" cellpadding="3">
<input type="text" name="BLNO" class="main_input" value = "<%=blno%>"size="20" __onBlur="checkBLNo(this)" onKeyDown="EnterCheck()">
<img src="../img/btn_multifile_upload.gif" width="92" height="18" border="0"
onmouseover="this.style.cursor='hand'"
onClick="goUrl('','/servlet/paperless.SwbUploadServlet')"/>
<input type="hidden" name="PROCESS_TYPE" value="CARRIER"/>
</table>
</form>
#####################################################################
23. 데이터베이스 커넷션하고 로그파일을 만듬
#####################################################################
package common;
import BrokerBean;
import javax.servlet.jsp.PageContext;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class SystemUsageHandler {
synchronized public static void insertLog(PageContext jspContext, String id, String menu, String func, String comment) throws SQLException, Exception
{
BrokerBean brokerBean = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
brokerBean = (BrokerBean) jspContext.getServletContext().getAttribute("DBPOOL");
conn = brokerBean.getDbConnection();
conn.setAutoCommit(false);
pstmt = conn.prepareStatement("insert into SYSTEM_USAGE_DETAIL (USER_ID, MENU, FUNC, COMMON ) "
+ " values (?,?,?,?)");
pstmt.setString(1, id);
pstmt.setString(2, menu);
pstmt.setString(3, func);
pstmt.setString(4, comment);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
conn.rollback();
} catch (Exception e) {
e.printStackTrace();
conn.rollback();
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) brokerBean.freeConnection(conn);
} catch (Exception ae) {
ae.printStackTrace();
}
}
}
}
#####################################################################
#####################################################################
01. ServerSocket 과 Socket 간의 채팅 소스
#####################################################################
import java.io.*;
import java.net.*;
import java.util.*;
public class Server_15
{
public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket(9999);
while (true)
{
System.out.println("Server Ready");
Socket socket = server.accept();
ServerHandle_15 sh = new ServerHandle_15(socket);
Thread th = new Thread(sh);
th.start();
}
}catch (IOException e){}
}
}
class ServerHandle_15 implements Runnable
{
private DataInputStream dis = null;
private DataOutputStream dos = null;
private Socket socket = null;
public static Vector v = new Vector();
public ServerHandle_15(Socket socket){
try
{
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
v.addElement(this);
}catch (IOException e){}
}
public void run(){
try
{
while (true)
{
String str = dis.readUTF();
broad(str);
}
}catch (IOException e){}
}
public void broad(String str){
for (int i=0; i<v.size() ; i++)
{
try
{
ServerHandle_15 sh = (ServerHandle_15)v.elementAt(i);
sh.dos.writeUTF(str);
}catch (IOException e){ }
}
}
};
import java.io.*;
import java.net.*;
public class Client_15 implements Runnable
{
private DataInputStream dis = null;
private DataOutputStream dos = null;
private Socket socket = null;
public Client_15()
{
try
{
socket = new Socket("localhost", 9999);
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
Thread th = new Thread(this);
th.start();
display();
}catch (IOException e){}
}
public void run(){
try
{
while (true)
{
String str = dis.readUTF();
System.out.println(str);
}
}catch (IOException e){}
}
public void display(){
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
String str = br.readLine();
dos.writeUTF(str);
}
}catch (IOException e){}
}
public static void main(String[] args){
Client_15 sc = new Client_15();
}
}
#####################################################################
#####################################################################
02. Swing에서 이미지 아이콘 삽입 및 종료
#####################################################################
import java.awt.*;
import javax.swing.*;
JFrame: Construct
private Container con;
con = this.getContentPane();
con.add(jbutton);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //플레임 종료
ImageIcon:
ImageIcon im = new ImageIcon("aa.gif");
this.setIconImage(im.getImage());
#####################################################################
#####################################################################
03. RMI 정상적인 예제
#####################################################################
package ksh.first;
import java.rmi.*;
public interface FirstRMI extends Remote{
String getString() throws RemoteException;
//void setString(String str) throws RemoteException;
}
#####################################################################
package ksh.first;
import java.rmi.*;
import java.rmi.server.*;
public class SecondRMI extends UnicastRemoteObject implements FirstRMI{
public SecondRMI() throws RemoteException{
super();
}
public String getString() throws RemoteException{
return "Hello RMI!!!";
}
}
#####################################################################
import ksh.first.*;
import java.rmi.*;
import java.net.*;
public class ThirdRMI{
public static void main(String[] ar){
SecondRMI sr = null;
try{
sr = new SecondRMI();
Naming.rebind("first", sr);
System.out.println("Server Ready...");
}catch(RemoteException ee){
}catch(MalformedURLException ee){}
}
}
#####################################################################
import ksh.first.*;
import java.rmi.*;
import java.net.*;
public class FourthRMI{
public static void main(String[] ar){
FirstRMI fr = null;
try{
fr = (FirstRMI)Naming.lookup("rmi://192.168.0.155/first");
String str = fr.getString();
System.out.println("실행된 메시지 = " + str);
}catch(NotBoundException ee){
}catch(MalformedURLException ee){
}catch(RemoteException ee){}
}
}
#####################################################################
#####################################################################
04. RMI registry 등록하지 않고 사용
#####################################################################
package ksh.second;
import java.rmi.*;
public interface FirstRMI extends Remote{
String getString() throws RemoteException;
}
#####################################################################
package ksh.second;
import java.rmi.*;
import java.rmi.server.*;
public class SecondRMI extends UnicastRemoteObject implements FirstRMI{
public SecondRMI() throws RemoteException{
super();
}
public String getString() throws RemoteException{
return "Hello RMI2!!";
}
}
#####################################################################
import ksh.second.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class ThirdRMI{
public static void main(String[] ar){
Registry rg = null;
SecondRMI sr = null;
try{
rg = LocateRegistry.createRegistry(2000);
sr = new SecondRMI();
Naming.rebind("rmi://192.168.0.155:2000/second", sr);
System.out.println("Server Ready...");
}catch(RemoteException ee){
}catch(MalformedURLException ee){}
}
}
#####################################################################
import ksh.second.*;
import java.rmi.*;
import java.net.*;
public class FourthRMI{
public static void main(String[] ar){
FirstRMI fr = null;
try{
fr = (FirstRMI)Naming.lookup(
"rmi://192.168.0.155:2000/second");
String str = fr.getString();
System.out.println("메시지 = " + str);
}catch(NotBoundException ee){
}catch(MalformedURLException ee){
}catch(RemoteException ee){}
}
}
#####################################################################
#####################################################################
05. RMI 통신법
#####################################################################
기본 Port 1099
Remote Method Invocation
rmi package & 중요 클래스
---------------------------------------------------------------------
1.서버: 공통 인터페이스, 구현 클래스, 스켈레톤 클래스, 서버실행 클래스
서버기동 bind(String str, Remote obj)
- 공통 인터페이스
public 인터페이스, Remote 인터페이스를 상속
abstract Method RemoteException 를 처리
매개변수들은 객체이거나 직렬화가 가능
- 구현클래스
public class Second extends UnicastRemoteObject implements FirstRMI 를 상속
- 스텝과 스켈레톤 계증 만들기
rmic -d . ksh.first.SecondRMI 구현클래스로 생성한다.
- rmiregistry 기동해야 한다. 1099번 Port 이용
대체클래스로 기동할 수도 있다
start rmiregistry 새창으로 돌려라 (unix에 백앤드 프로그램 생성하는 것과 같다)
- Binding 시키기 (등록시킨다)
ThirdRMI {
SecondRMI sr = new SecondRMI();
sr.rebind("first", sr);
}
C\>start java ThirdRMI 로 실행
#####################################################################
2.클라이언트: 공통인터페이스, 스넵 클래스, GUI 클래스
- 서버 파일 가져오기, 스텝 클래스를 가져온다
공통인터페이스 FirstRMI.class, SecondRMI_Stub.class
- 서버의 기동중인 객체를 얻어오기
import ksh.first.*;
import java.rmi.*;
public class FourthRMI{
try
{
FirstRMI fr = new First();
fr = (FirstRMI)Naming.lookup("rmi://165.213.42.29:1099/first");
}
catch (NotBoundException e){}
catch (MalformedURLException e){}
catch (RemoteException e){}
}
- 해당 객체를 통해서 Method 를 사용하기
String str = fr.getString();
System.out.println("얻어온 실행된 메시지 "+str);
#####################################################################
3. rmiregistry 대체 클래스
Registry interface (Naming class 와 유사)
LocateRegistry class
import ksh.second.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class ThirdRMI
{
public static void main(String[] args){
SecondRMI sc = null;
Registry rg = null;
try
{
rg = LocateRegistry.createRegistry(2000);
sc = new SecondRMI();
Naming.rebind("rmi:192.168.0.155:2000/second", sc);
}
catch (RemoteException e){}
catch (MalformedURLException e){}
}
};
#####################################################################
#####################################################################
06. Directory 찾아서 리스트 만들기
#####################################################################
import java.io.*;
public class MakeFileList
{
PrintWriter pw = null;
public MakeFileList(){
try
{
FileOutputStream fos = new FileOutputStream(new File("./Text.txt"));
OutputStreamWriter osw = new OutputStreamWriter(fos, "EUC-KR");
pw = new PrintWriter(osw, true);
}catch (IOException e){
System.out.println("File write error "+e);
}
searchDirectory(new File("."));
pw.flush();
pw.close();
}
public void searchDirectory(File here){
File[] rootFileList = here.listFiles();
for (int i=0; i<rootFileList.length ; i++ )
{
if (rootFileList[i].isDirectory())
{
searchDirectory(rootFileList[i]);
}else{
try
{
String filename = rootFileList[i].getName();
String ext = filename.substring(filename.lastIndexOf("."), filename.length());
if (!ext.equalsIgnoreCase(".gif") && !ext.equalsIgnoreCase(".jpg") )
{
pw.print(rootFileList[i].toURL());
pw.print("\n");
System.out.println(rootFileList[i].toURL());
}else{
System.out.println(ext);
}
}catch (Exception e){}
}
}
}
public static void main(String[] args){
MakeFileList mf = new MakeFileList();
}
};
#####################################################################
#####################################################################
07. IO 관련 소스
#####################################################################
Abstract OutStream을 이용한 입력하기
ch01 - AAA - Exam02_01.java, jar02.jar (jar -cvf jar02.jar *.*)
BBB - Exam02_Main.java
jar 위치: C:\jdk1.3.1\jre\lib\ext\jar02.jar
private PrintStream ps;
public Exam02_03(){
super();
ps = System.out;
}
public void write(int i){
ps.write(i);
ps.flush();
}
public void close(){
ps.close();
}
Exam02_03 es = new Exam02_03();
es.write(65);
es.write('\r');
es.write('\n');
byte[] bb = {'h','e','l','l','o'};
es.write(bb);
//es.close();
byte[] cc = "HELLO JAVA".getBytes();
es.write('\r');
es.write('\n');
es.write(cc, 0, 5);
es.write("송하연".getBytes("ISO8859_1"));
#####################################################################
private InputStream is;
public Exam02_04(){
super();
is = System.in;
}
public int read() throws IOException{
int xx = is.read();
if (xx == '\n')
{
return -1;
}
return xx;
}
/*
byte[] bb = new byte[20];
System.out.print("입력 ");
System.in.read(bb);
int i = System.in.read();
System.out.println("입력된 문자 "+ new String(bb));
*/
Exam02_04 es = new Exam02_04();
byte[] bb = new byte[20];
System.out.print("입력 : ");
es.read(bb);
System.out.println("입력된 문자 : "+ new String(bb));
#####################################################################
#####################################################################
08. 파일을 읽는 소스
#####################################################################
int cnt;
FileReader rf = new FileReader("Test.java");
cnt = rf.read();
while (cnt != -1)
{
System.out.print(cnt);
cnt = rf.read();
}
#####################################################################
#####################################################################
09. 입력받은 파일을 읽는 소스
#####################################################################
int cnt = 0;
System.out.print("Input your filename ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
RandomAccessFile raf = new RandomAccessFile(str, "r");
cnt = raf.read();
while (cnt != -1)
{
System.out.print((char)cnt);
cnt = raf.read();
}
#####################################################################
#####################################################################
10. 스트링을 파일로 저장하는 소스
#####################################################################
String str = "어디로 가야 할지";
char[] ch = new char[str.length()];
str.getChars(0, ch.length, ch, 0);
FileWriter fw = new FileWriter(args[0]);
fw.write(ch);
fw.close();
#####################################################################
#####################################################################
11. 파일을 저장하는 소스
#####################################################################
FileOutputStream fos = new FileOutputStream(args[0]);
for (int i=0; i<500 ; i++ )
{
fos.write(i);
}
fos.close();
System.out.println("FileOutputStream 했습니다!");
#####################################################################
#####################################################################
12. 에디터에는 볼 수 없으나 도스에서는 보임
#####################################################################
int cnt;
FileInputStream fis = new FileInputStream(args[0]);
while ( (cnt = fis.read()) != -1)
{
System.out.println(cnt);
}
System.out.println("FileInputStreamDemo를 확인했습니다.");
#####################################################################
#####################################################################
13. Properties 파일에 관련된 소스
#####################################################################
파일과 관련해서 Properties 저장하는 소스
Properties props = new Properties();
props.put("이름","마법사프로퍼티");
props.put("주소","마법의나라");
props.store(new FileOutputStream("properties.dat"),"프로퍼트테스트");
#####################################################################
#####################################################################
14. 파일과 관련해서 Properties 에서 읽어 오는 소스
#####################################################################
Properties props = new Properties();
props.load(new FileInputStream("properties.dat"));
System.out.println("이름: "+props.getProperty("이름"));
System.out.println("주소: "+props.getProperty("주소"));
#####################################################################
#####################################################################
15. 읽은 파일입력 후 내용확인하는 소스
#####################################################################
String fileInput;
int c = 0;;
System.out.print("Input your file name ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
fileInput = br.readLine();
RandomAccessFile raf = new RandomAccessFile(fileInput, "r");
c = raf.read();
while ( c != -1 )
{
System.out.print((char)c);
c = raf.read();
}
raf.close();
#####################################################################
#####################################################################
16. 입력파일과 저장할 파일을 쓰는 소스
#####################################################################
String fileinput;
String fileoutput;
int c;
System.out.print("Input your filename ");
BufferedReader bf1 = new BufferedReader(new InputStreamReader(System.in));
fileinput = bf1.readLine();
System.out.print("Write save filename ");
BufferedReader bf2 = new BufferedReader(new InputStreamReader(System.in));
fileoutput = bf2.readLine();
RandomAccessFile raf1 = new RandomAccessFile(fileinput, "r");
RandomAccessFile raf2 = new RandomAccessFile(fileoutput, "rw");
c = raf1.read();
while (c!=-1)
{
raf2.write(c);
System.out.print((char)c);
c = raf1.read();
}
raf1.close();
raf2.close();
#####################################################################
#####################################################################
17. 파일을 읽어서 보여주는 소스
#####################################################################
FileInputStream fis = new FileInputStream("Tst.java");
byte[] byteTxt = new byte[fis.available()];
fis.read(byteTxt);
fis.close();
System.out.println(new String(byteTxt));
#####################################################################
#####################################################################
18. 2초마다 출력하는 쓰레드 소스
#####################################################################
public class ThreadFromThread extends Thread
{
public static void main(String[] args)
{
ThreadFromThread tt = new ThreadFromThread();
tt.start();
}
public void run(){
try{
for(int i=0; i<10; i++)
{
Thread.sleep(2000);
System.out.println(i + " 2초 마다 출력되는 소스 !!!");
}
}
catch(InterruptedException e){}
}
};
#####################################################################
#####################################################################
19. 배열과 관련하여
#####################################################################
2차원 배열 출력하는 소스
int[][] aa =
{
{1, 6, 11, 16, 21},
{2, 7, 12, 17, 22},
{3, 8, 13, 18, 23},
{4, 9, 14, 19, 24},
{5, 10, 15, 20, 25}
};
for (int i=0; i<aa.length ; i++)
{
if (i<5)
{
for (int j=0; j<aa[i].length ; j++ )
{
System.out.print(aa[i][j] +" ");
}
System.out.println();
}
}
#####################################################################
#####################################################################
20. 배열로 합계 평균을 내는 소스
#####################################################################
int sum = 0;
long average = 0;
int[] aa = {20, 30, 40, 50, 30, 70};
int len = aa.length;
for (int i=0; i<aa.length ; i++)
{
sum += aa[i];
}
System.out.println("sum ->/"+sum+"/");
System.out.println("average ->/"+(long)sum/len+"/");
#####################################################################
#####################################################################
21. 프로그램 인수를 받아 평균과 총계를 보여주는 소스
#####################################################################
if ( args.length<1 )
{
System.out.println("Usage : java ArrayDe_05 ");
System.exit(-1);
}
int aa = Integer.parseInt(args[0]);
int[] bb = new int[aa];
for (int i=0; i<bb.length ; i++ )
{
bb[i] = i+1;
}
int sum = 0;
long average = 0;
int len = bb.length;
for (int i=0; i<bb.length ; i++ )
{
sum += bb[i];
}
System.out.println("sum ->/"+sum+"/");
System.out.println("average ->/"+(long)sum/len+"/");
#####################################################################
#####################################################################
22. [실행되지 않으나 참고해야 할 소스]
#####################################################################
프로그램 실행시간을 체크하는 소스
CronLog cl = new CronLog("Maker.log");
Date dSTART_PROG = new Date();
중간 프로세스 처리
Date dEND_PROG = new Date();
long lELAPSED = dEND_PROG.getTime() - dSTART_PROG.getTime();
cl.log("Making started at " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dSTART_PROG));
cl.log("Making ended at " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dEND_PROG));
cl.log("Making " + lELAPSED / 1000 + " seconds elapsed.");
#####################################################################
#####################################################################
23. 로그 관련 소스
#####################################################################
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class CronLog {
private String sLOG_FILE = null, sLOG_PATH = null;
private PrintStream out = null;
SimpleDateFormat formatter;
int iBACKUPFILE_KEEPING_DURATION = 30; // 로그 파일 보관 일수(디폴트 30일)
public CronLog() {
sLOG_FILE = makeLogFileName(Calendar.getInstance(), "MINU.log");
formatter = new SimpleDateFormat("HH:mm:ss");
removeLog( sLOG_FILE );
}
public CronLog(String sLOG_FILENAME) {
sLOG_FILE = makeLogFileName(Calendar.getInstance(), sLOG_FILENAME);
formatter = new SimpleDateFormat("HH:mm:ss");
removeLog( sLOG_FILE );
}
public CronLog(String sLOG_FILENAME, int iBACKUPFILE_KEEPING_DURATION) {
sLOG_FILE = makeLogFileName(Calendar.getInstance(), sLOG_FILENAME);
formatter = new SimpleDateFormat("HH:mm:ss");
this.iBACKUPFILE_KEEPING_DURATION = iBACKUPFILE_KEEPING_DURATION;
removeLog( sLOG_FILE );
}
/** 해당 주기(iBACKUPFILE_KEEPING_DURATION)에 따라 로그 파일을 삭제함... */
public void removeLog(String sLOG_FILE) {
String sLOG_PATH = sLOG_FILE.substring(0, sLOG_FILE.lastIndexOf(File.separator)+1);
if( sLOG_PATH.trim().equals("") ) {
sLOG_PATH = ".";
}
File fLOG_PATH = new File(sLOG_PATH);
if( fLOG_PATH.isDirectory() ) {
File[] foLOG_FILES = fLOG_PATH.listFiles();
for(int i=0; i<foLOG_FILES.length; i++) {
File fLOG_FILE = foLOG_FILES[i];
long lLOG_FILE_ELAPSED = (new Date().getTime() - fLOG_FILE.lastModified()) / (24 * 60 * 60 * 1000);
if( fLOG_FILE.isFile() && lLOG_FILE_ELAPSED >= iBACKUPFILE_KEEPING_DURATION) {
fLOG_FILE.delete();
}
}
}
}
public void log(String sLOG) {
if( sLOG_FILE == null ) {
sLOG_FILE = makeLogFileName(Calendar.getInstance(), "MINU.log");
}
if( out == null ) {
File fLOG_FILE = new File(sLOG_FILE);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(sLOG_FILE, true);
} catch (FileNotFoundException e) {
System.err.println(e.toString());
}
out = new PrintStream(fos);
}
out.println("[" + formatter.format(new Date()) + "] " + sLOG);
}
public static String makeLogFileName(Calendar cal, String name) {
java.util.Date dt = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("@yyyy-MM-dd");
String dateString = formatter.format(dt);
int ind = name.indexOf(".");
String head = name.substring(0, ind);
String tail = name.substring(ind);
name = head + dateString + tail;
checkDirectory(new File(name.substring(0, name.lastIndexOf(File.separator))));
return name;
}
public static File checkDirectory(File dir) {
File retVal = null;
try {
if (!dir.isDirectory()) {
if (dir.mkdir()) {
System.out.println("[" + dir.toString() + "] Directory Created, sucessfully.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dir;
}
public static void main(String[] args) {
CronLog l = new CronLog("KKK.LOG");
for(int i=0; i<100; i++ ) {
l.log(String.valueOf(i));
}
l.log("한글은???????????????????????????");
l.log("Enddddddddddddddddddddddddddddddd");
}
public void log(int i) {
log(String.valueOf(i));
}
}
#####################################################################
|