지정된 양식에 하나의 ROW만 존재한 상황에서

두번째 줄부터는 아래와 같은 함수를 이용하여 값을 write한다.


1) ROW가 있는지 확인

 - 해당 ROW가 정해져있는 양식이 있는지 확인

 - 없으면 create row


2) Cell이 있는지 확인

 - 해당 ROW는 위에서 만들었기 때문에 존재함.

 - 해당 ROW, CELL에 정해져 있는 양식이 있는지 확인

 - 없으면 create cell 

 - 바로 위 row에서 style을 가지고와서 지정

 - 값 wirte



protected void writeLabelCell(HSSFSheet sheet, int _row, int _col, String str){

try{

HSSFRow row = sheet.getRow(_row);

if(row == null){ 

row = sheet.createRow(_row);

}

HSSFCell cell = row.getCell(_col);

if(cell == null){ // CELL이 없으면 바로 위 행의 ROW의 CELL 스타일을 가지고 옴.

HSSFRow refRow = sheet.getRow((_row-1));

HSSFCell refCell = refRow.getCell(_col);

cell = row.createCell(_col);

cell.setCellStyle(refCell.getCellStyle());

}


try{

row = sheet.getRow(_row);

cell = row.getCell(_col);

cell.setCellValue(str);

}catch(Exception e){

e.printStackTrace();

}

}catch(Exception e){

e.printStackTrace();

}

}

Statement를 사용하지 말고 PreparedStatement를 사용하라고 권장 하더라..


아래는 예제


public void add(User user) throws ClassNotFoundException, SQLException{

Class.forName("com.mysql.jdbc.Driver");

Connection c = DriverManager.getConnection("jdbc:mysql://localhost/test", "sa", "pw!");

PreparedStatement ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");

ps.setString(1, user.getId());

ps.setString(2, user.getName());

ps.setString(3, user.getPassword());

ps.executeUpdate();

ps.close();

c.close();

}

public User get(String id) throws ClassNotFoundException, SQLException{

Class.forName("com.mysql.jdbc.Driver");

Connection c = DriverManager.getConnection("jdbc:mysql://localhost/test", "sa", "pw!");

PreparedStatement ps = c.prepareStatement("select * from users where id = ?");

ps.setString(1, id);

ResultSet rs = ps.executeQuery();

rs.next();

User user = new User();

user.setId(rs.getString("id"));

user.setId(rs.getString("name"));

user.setId(rs.getString("password"));

rs.close();

ps.close();

c.close();

return user;

}

try {
   Enumeration<NetworkInterface> e= NetworkInterface.getNetworkInterfaces();
            while(e.hasMoreElements())
            {
                NetworkInterface n = e.nextElement();
                Enumeration<InetAddress> ee = n.getInetAddresses();
               
                while(ee.hasMoreElements())
                {
                    InetAddress i= (InetAddress) ee.nextElement();
                    String ip = i.getHostAddress().toString();
                   
                    StringTokenizer str = new StringTokenizer(ip, ".");
                    if(str.countTokens() == 4){
                     if(!ip.equals("127.0.0.1")){
                      System.out.println(ip);
                     }
                    }
                }
            }
  }
  catch (Exception e) {
   e.printStackTrace();
  }

o Set 객체

 - HashSet : 동기화 안됨. 가장 빠른 집합. HashMap 보다 느리지만 Set 인터페이스를 구현하고 있다.
   HashMap 은 Set 이 아니라 Map 이다.
 - TreeSet : 동기화 안됨. HashSet보다 느리다. 차례대로 키를 사용할 수 있다. (키가 정렬됨)
 
o Map 객체
 - HashMap : 동기화 안됨. 가장 빠른 매핑.
 - Hashtable : 동기화 됨. HashMap 보다 느리지만 동기화한 HashMap 보다 빠르다.
 - TreeMap : 동기화 안됨. Hashtable 과 HashMap 보다 느리다. 차례대로 키를 사용할 수 있다. (키가 정렬됨)
 
o List 객체
 - ArrayList : 동기화 안됨. 가장 빠른 리스트.
 - LinkedList : 동기화 안됨. 다른 리스트보다 느리지만 큐로 이용했을 경우 더 빠를 수도 있다.
   느린 이유는 ArrayList나 Vector, Stack 과 달리 array 계열이 아니기 때문.
 - Vector : 동기화 됨. ArrayList 보다 느리지만 동기화한 ArrayList 보다 빠르다.
 - Stack : 동기화 됨. Vector 와 동일한 속도. LIFO 큐 기능을 제공한다.


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

public class MemoryMonitor {
 public static List listRunningProcesses(String processName) {
  List processes = new ArrayList();
  try {
   String line;
   StringTokenizer temp;
   Process p = Runtime.getRuntime().exec("tasklist.exe /FI \"IMAGENAME eq \""+processName+" /FO CSV /NH");
   BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
   while ((line = input.readLine()) != null) {
    if (!line.trim().equals("")) {
     // keep only the proecess name
     line = line.replace("\",\"", "^").replace("\"", "").replace(",", "");
     temp = new StringTokenizer(line, "^");
     while (temp.hasMoreTokens()) {
      processes.add(temp.nextToken());
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return processes;
 }

 public static void main(String[] args) {
  List processes = listRunningProcesses("svchost.exe");
  String result = "";
  // display the result
  Iterator it = processes.iterator();

  int i = 0;
  while (it.hasNext()) {
   result += it.next() + "\n";
   i++;
   if (i % 5 == 0)
    result += "\n";
  }
  System.out.println(result);
 }

 public void start() {
  // TODO Auto-generated method stub
  
 }
}

'JAVA' 카테고리의 다른 글

IP찾기  (0) 2013.02.26
Java - 자주사용하는 Collection객체들의 특징  (0) 2013.02.08
[JAVA] String의 날짜를 date로 변환  (0) 2013.01.25
[JAVA] 파일 읽고, 쓰기  (0) 2013.01.24
[JAVA] log4j  (0) 2009.11.12

사각형 중 라인 표시 하고 싶으면 1 아니면 0

BorderFactory.createMatteBorder(0, 0, 1, 0, Color.black));

 

public static MatteBorder createMatteBorder(int top,
                                            int left,
                                            int bottom,
                                            int right,
                                            Color color)

날짜의 예) 2013-01-24 17:01:54

String writeDate = "2013-01-24 17:01:54";

SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss", Locale.KOREA);

sdf.parse(writeDate)

 

추가로 String을 Timestamp로 변환할 때는

Timestamp.valueOf(wirteDate);

'JAVA' 카테고리의 다른 글

IP찾기  (0) 2013.02.26
Java - 자주사용하는 Collection객체들의 특징  (0) 2013.02.08
[JAVA] 프로세스 리스트 출력 - 확인해보기  (0) 2013.02.08
[JAVA] 파일 읽고, 쓰기  (0) 2013.01.24
[JAVA] log4j  (0) 2009.11.12

파일 읽기 :

FileReader fileReader = new FileReader (fileName);
   BufferedReader bufferedReader = new BufferedReader(fileReader);
   String str = "";
   while ((str=bufferedReader.readLine()) != null ){
    System.out.println(str); 
   }

fileReader.close();

 

 

 

파일쓰기 :

fileWriter = new FileWriter(new File(fileName));

fileWriter.write(str.toString());

fileWriter.close();

'JAVA' 카테고리의 다른 글

IP찾기  (0) 2013.02.26
Java - 자주사용하는 Collection객체들의 특징  (0) 2013.02.08
[JAVA] 프로세스 리스트 출력 - 확인해보기  (0) 2013.02.08
[JAVA] String의 날짜를 date로 변환  (0) 2013.01.25
[JAVA] log4j  (0) 2009.11.12

프로그램을 하다가 오류나 디버깅을 하기 위해 System.out.println으로 출력을 많이한다.

하지만 log4j라는 것을 이용하여 일반 디버깅 보다는 적절하게

console, file, smtp, db 등 여러곳으로 로그를 남길수 있는게 log4j이다.

프로퍼티 파일을 이용하여 사용할 수도 있고 .

이렇게 어플리 케이션에서 사용할 수 도 있다.


fatal(), error(), warn(), info(), debug(), trace()
fatal : 아주 심각한 에러가 발생한 상태를 나타낸다. 시스템적으로 심각한 문제가 발생해서 어플리케이션 작동이 불가능할 경우가 해당하는데, 일반적으로는 어플리케이션에서는 사용할 일이 없다.
error : 요청을 처리하는중 문제가 발생한 상태를 나타낸다.
warn  : 요청을 처리하는중 문제가 발생했지만, 불완전하게나마 처리가 가능한 상태를 나타낸다.
info : 어플리케이션이 작동할때 필요한 기본적인 정보를 나타낸다.
debug : 디버깅 즉, 문제 해결을 하기 위한 상태 정보를 나타낸다.
trace : log4j1.2.12에서 신규 추가된 레벨으로서. 디버그 레벨이 너무 광범위한것을 해결하기위해서 좀더 상세한 상태를 나타낸다.


######################################################################
#%p  debug, info, warn, error, fatal 등의 priority 가 출력된다. 
#%m  로그내용이 출력됩니다
#%d  로깅 이벤트가 발생한 시간을 기록합니다.
#  포맷은 %d{HH:mm:ss, SSS}, %d{yyyy MMM dd HH:mm:ss, SSS}같은 형태로 사용하며 SimpleDateFormat에 따른 포맷팅을 하면 된다
#%t  로그이벤트가 발생된 쓰레드의 이름을 출력합니다. 
#%%  % 표시를 출력하기 위해 사용한다. 
#%n  플랫폼 종속적인 개행문자가 출력된다. \r\n 또는 \n 일것이다. 
#%c  카테고리를 표시합니다
#  예) 카테고리가 a.b.c 처럼 되어있다면 %c{2}는 b.c가 출력됩니다.
#%C  클래스명을 표시합니다.
#  예)클래스구조가 org.apache.xyz.SomeClass 처럼 되어있다면 %C{2}는 xyz.SomeClass 가 출력됩니다
#%F  로깅이 발생한 프로그램 파일명을 나타냅니다.
#%l  로깅이 발생한 caller의 정보를 나타냅니다
#%L  로깅이 발생한 caller의 라인수를 나타냅니다
#%M  로깅이 발생한 method 이름을 나타냅니다.
#%r  어플리케이션 시작 이후 부터 로깅이 발생한 시점의 시간(milliseconds)
#%x  로깅이 발생한 thread와 관련된 NDC(nested diagnostic context)를 출력합니다.
#%X  로깅이 발생한 thread와 관련된 MDC(mapped diagnostic context)를 출력합니다.

#######################################################################


  

import java.io.*;
import org.apache.log4j.*;
import org.apache.log4j.net.SMTPAppender;
import org.apache.log4j.jdbc.JDBCAppender;

public class Test2 {
 
 
 public static Logger logger = Logger.getRootLogger();
 
 String logPattern = "[%d][%-5p](%F:%L) - %m%n";
 DailyRollingFileAppender fileAppd = null;
 ConsoleAppender conAppd = null;
 JDBCAppender dbAppd = null;
 
 public void fileAppend(){
  
  try{
   
   fileAppd = new DailyRollingFileAppender(new PatternLayout(logPattern), "./log/logfile.log", "yyyy-MM-dd");
   
  }catch (IOException e){
   System.out.println("file 로그설정에 문제");
   System.exit(-1);
  } 
  //fileAppd.setThreshold(Level.FATAL); // 이것보다 레벨이 낮으면 안됨
  
  logger.addAppender(fileAppd);
 }
 
 public void consoleAppend(){


  try{
   conAppd = new ConsoleAppender(new PatternLayout(logPattern));
   
  }catch (Exception e){
   
   System.out.println("consol 로그설정에 문제");
   System.exit(-1);
  }
  //conAppd.setThreshold(Level.TRACE); // 이것보다 레벨이 낮으면 안됨
  logger.addAppender(conAppd);
 }
 
 public void smtpAppend(){
 
  SMTPAppender appender = null;
  try{
   appender = new SMTPAppender();
   appender.setBufferSize(1);
   appender.setTo("받는사람");
   appender.setFrom("보내는사람");
   appender.setSMTPHost("메일호스트");
   appender.setSubject("제목");
   
   appender.setLayout(new PatternLayout(logPattern));
   appender.activateOptions();
   
  }catch (Exception e){
   System.out.println("smtp 로그설정에 문제");
   System.exit(-1);
  }
  logger.addAppender(appender);
 } 
 
 public void dbAppend(){
  try{
   dbAppd = new JDBCAppender();
   dbAppd.setDriver("com.microsoft.jdbc.sqlserver.SQLServerDriver");
   dbAppd.setURL("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=디비이름");
   dbAppd.setUser("사용자이름");
   dbAppd.setPassword("비번");
   dbAppd.setLayout(new PatternLayout(logPattern));
   dbAppd.setBufferSize(1);
   dbAppd.setSql("insert into APP_LOG(LOGDATE, LOGLEVEL, CLASSNAME, LINE, MESSAGE) values('%d', '%p', '%F', '%L', '%m')");
   
  }
  catch(Exception e){
   System.out.println("db 로그설정에 문제");
   System.exit(-1);
  } 
  logger.addAppender(dbAppd);
 }
 
 public void setLogFatal(String message){
  logger.fatal(message);
 }
 public void setLogDebug(String message){
  logger.debug(message);
 }
 public void setLogWarn(String message){
  logger.warn(message);
 }
 public void setLogInfo(String message){
  logger.info(message);
 }
 public void setLogTrace(String message){
  logger.trace(message);
 }
 public void setLogError(String message){
  logger.error(message);
 }
 
 
}

 

 


+ Recent posts