달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

http://suite.tistory.com  2018.01  fs


* 시간 등록일 표시를 줄여서 표시

ex) 1년전 , 3개월전 1주전 , 2일전, 5분전 , 1분전, 1초전 

 

joda 라이브러리 이용  import org.joda.time.Interval;import org.joda.time.Period;


public String getSummaryPeriod(Date date) {
String resultPeriod = "";
Interval interval = new Interval(date.getTime(), new Date().getTime());
Period period = interval.toPeriod();
if (period.getYears() > 0) {
resultPeriod = period.getYears() + "년 전";
} else if (period.getMonths() > 0) {
resultPeriod = period.getMonths() + "개월 전";
} else if (period.getWeeks() > 0) {
resultPeriod = period.getWeeks() + "주 전";
} else if (period.getHours() > 0) {
resultPeriod = period.getDays() + "일 전";
} else if (period.getWeeks() > 0) {;
resultPeriod = period.getHours() + "시간 전";
} else if (period.getMinutes() > 0) {
resultPeriod = period.getMinutes() + "분 전";
} else if (period.getSeconds() > 0) {
resultPeriod = period.getSeconds() + "초 전";
}

return resultPeriod;
}



* 읽은 수 카운트 줄여서  표시

 ex) 1천 , 1.2만 , 1.5억  대략적인 수치로 줄임

참고소스 https://stackoverflow.com/questions/4753251/how-to-go-about-formatting-1200-to-1-2k-in-java

public String getSummaryCount(int count) throws IOException {
if (count < 1000) {
return "" + count;
}
int div = 4;
if (count < 10000) {
div = 3;
}
double value = count;
String suffix = "천만억";
String formattedNumber = "";
NumberFormat formatter = new DecimalFormat("#,###.#");
int power = (int) StrictMath.log10(value);
value = value / (Math.pow(10, (power / div) * div));
formattedNumber = formatter.format(value);
formattedNumber = formattedNumber + suffix.charAt(power / 4);
return formattedNumber;
}



:
Posted by mastar

2015.07 http://suite.tistory.com/


package 화된 jar 파일내 파일 읽기 함수 샘플


1. 파일 존재 확인 


if( this.getClass().getResource( "/file name") == null ) 이면 없는 거임

  * 절대 경로로 / 부터 찾기   , jar fxv pack.jar 풀어서 경로를 미리 보고 입력해도 됨 


2. stream -> BufferedReader -> readLine 


BufferedReader in=new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream( "/file name"), "UTF-8"));

String strLine = "";

while ((strLine = in.readLine()) != null) {

System.out.println("readLine"  + strLine);

}


:
Posted by mastar

http://suite.tistory.com  fs 2012.10 

 

매번 검색해서 사용하던거 정리 

java.lang.OutOfMemoryError: Java heap space 에러나지 MAX_BUF_BYTE 단위로 loop !


※ Buffered*클래스 사용하면 큰파일에 유리하다고 구글링!~ 

 

1.  InputStream 으로 파일 쓰기

 		private final int MAX_BUF_BYTE = 1024000; 

		FileInputStream in = null;
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		try {

			
			byte[] buffer = new byte[MAX_BUF_BYTE];

			in = new FileInputStream(new File("file"));
			fos = new FileOutputStream(filename);
			bis = new BufferedInputStream(in);

			bos = new BufferedOutputStream(fos);
			int len = 0;
			while ((len = bis.read(buffer)) >= 0) {
				bos.write(buffer, 0, len);
			}

		} catch (Exception e) {
			LOG.info(e.toString());
		} finally {
			try {

				bos.close();
				bis.close();
				fos.close();
				in.close();
			} catch (Exception e) {
			}
		}


2.   stream을 byte 로 변환  

ByteArrayOutputStream 클래스 활용 


		InputStream in = null;
		BufferedInputStream bis = null;
		ByteArrayOutputStream arrayBuff = new ByteArrayOutputStream();
		try {

			byte[] buffer = new byte[MAX_BUF_BYTE];

			in=new FileInputStream(new File("readFile"));
			bis = new BufferedInputStream(in);
			int len = 0;
			while ((len = bis.read(buffer)) >= 0) {
				arrayBuff.write(buffer, 0, len);
			}

		} catch (Exception e) {
			LOG.info(e.toString());
		} finally {

			try {
		
				in.close();
				bis.close();

			} catch (Exception e) {
			}
		}
		return arrayBuff.toByteArray();


:
Posted by mastar
2012. 5. 30. 19:20

[ java ] javax.mail 참조 용 용-ILE/LANG-JAVA(JSP)2012. 5. 30. 19:20

suite.tistory.com 2012.05 fs

maven jar 파일 다운로드 설정

~~~~~~~~~~~~~~ pom.xml ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.2</version>
</dependency>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


  try {

   Properties props = new Properties();

   props.put("mail.transport.protocol", "smtp");

   props.put("mail.smtp.host", get("SMTP_HOST"));

   // props.put("mail.smtp.port", "25"); 안하면 기본 25번

   Session session = Session.getInstance(props);

   MimeMessage message = new MimeMessage(session);

   // ex ) format :fs<fs@naver.com>"
   int pos = senderEmail.indexOf("<");
   String senderName = "";
   if (pos != -1) {
    senderName = senderEmail.substring(0, pos);
    senderEmail = senderEmail.substring(pos);
    senderEmail = senderEmail.replaceAll("<|>", "");
   }
   message.setFrom(new InternetAddress(senderEmail, senderName));

   // ex ) format :"fs<fs@daum.net>"
   String recvName = "";
   pos = recvAddr.indexOf("<");
   if (pos != -1) {
    recvName = recvAddr.substring(0, pos);
    recvAddr = recvAddr.substring(pos);
    recvAddr = recvAddr.replaceAll("<|>", "");
   }
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(recvAddr, recvName));

   message.setSubject(title);

   message.setContent(contentBody, "text/html; charset=UTF-8");

   Transport.send(message);

  } catch (Exception e) {
      LOG.error(" #[FAIL]sendBySmtp: 메일 발송 오류 발생:" + e.toString());
  }

 

 

:
Posted by mastar
2011. 6. 18. 18:17

[java] Pascal Triangle by array 용-ILE/LANG-JAVA(JSP)2011. 6. 18. 18:17


fs 2011.06

파스칼 삼각형 상위값 합이 자기 값인거!! 자바 배열로 출력

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/**
 * <pre>
  * FileName  : pascalTriangle.java
  * Package   :
  * Comment   :
  * </pre>
  *
  * @author   : http://suite.tistory.com/
  * @date     : 2011. 6. 18.
 */
public class pascalTriangle {

 public static void main(String[] args) {
  int HEIGHT = 100;
  final int CNUM = 1;
  long[][] dataArray = new long[HEIGHT][];
  for (int i = 0; i < HEIGHT; i++) {
   int cnt = 0;
   dataArray[i] = new long[i + 1];
   for (int j = 0; j < i + 1; j++) {
    if (cnt == 0 || i == j) {
     dataArray[i][cnt++] = CNUM;
     continue;
    } else {
     long val = dataArray[i - 1][j] + dataArray[i - 1][j - 1]; // 바로 상위 두개 값 합
     dataArray[i][cnt++] = val;

    }
   }
  }
  // print
  for (int k = 0; k < HEIGHT; k++) {
   for (int idx = 0; idx < dataArray[k].length; idx++) {
    System.out.print(dataArray[k][idx] + " ");
   }
   System.out.println();
  }
 }
}


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
결과

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
......
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

:
Posted by mastar

http://suite.tistory.com  fs 2011.2                                      

자바에서 리스트 객체의 멤버 값에 따라 정렬시

Collections.sort() 를 사용해보는데 한개 변수로 올림/내림 차순 정렬외
한개의 변수의 값이 같을때 2차로 정렬을 할려고하니 검색해도 잘안나와 적어봄~~

ex) 포인트가 높고 같을때는 최신날짜 순으로 할때

1. 객체 class

public class box {
 int point;
 int date;
 String title;
}

2.비교함수용 implements Comparator 클래스

import java.util.Comparator;

class comparator implements Comparator<box> {

 public int compare(box box1, box box2) {

  int ret = 0;
  if (box1.point < box2.point) {
   ret = 1;
  }
  if (box1.point == box2.point) {
   if (box1.date < box2.date) {
    ret = 1;
   }
  }
  return ret;
 }
//문자열이면 compareTo()를 활용하면 될것같음
}


3. main 클래스

import java.util.ArrayList;
import java.util.Collections;

public class test1 {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  ArrayList<box> al = new ArrayList();

  box b1 = new box();
  b1.point = 100;
  b1.date = 201012;
  b1.title = "제목1";
  al.add(b1);
  box b2 = new box();
  b2.point = 200;
  b2.date = 201101;
  b2.title = "제목2";
  al.add(b2);

  box b3 = new box();
  b3.point = 200;
  b3.date = 201102;
  b3.title = "제목3";
  al.add(b3);

  System.out.println("정렬전");
  for (int i = 0; i < al.size(); i++) {
   System.out.print(al.get(i).title);
   System.out.print("," + al.get(i).point);
   System.out.println("," + al.get(i).date);
  }

  Collections.sort(al, new comparator());

  System.out.println("\n정렬후\n");
  for (int i = 0; i < al.size(); i++) {
   System.out.print(al.get(i).title);
   System.out.print("," + al.get(i).point);
   System.out.println("," + al.get(i).date);
  }
 }
}


4. 실행결과
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
정렬전
제목1,100,201012
제목2,200,201101
제목3,200,201102

정렬후

제목3,200,201102
제목2,200,201101
제목1,100,201012
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

:
Posted by mastar

http://suite.tistory.com 2010 12

이클립스 톰켓 plugin 의 WEB-INF/lib 에서 jsp-api-2.0.jar 삭제 하고 톰켓 리스타트~

 Unable to read TLD "META-INF/c.tld" from JAR file "file:/c:/org.eclipse.wst.server.core/tmp9/wtpwebapps/WEB-INF/lib/standard-1.1.2.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagLibraryValidator class: org.apache.taglibs.standard.tlv.JstlCoreTLV
org.apache.jasper.JasperException: Unable to read TLD "META-INF/c.tld" from JAR file "file:/C:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp9/wtpwebapps/WEB-INF/lib/standard-1.1.2.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagLibraryValidator class: org.apache.taglibs.standard.tlv.JstlCoreTLV
 at org.apache.jasper.compiler.DefaultErrorHandler/C:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp9/wtpwebapps/WEB-INF/lib/standard-1.1.2.jar

 

:
Posted by mastar

2010-11 http://suite.tistory.com 

샘플소스중에  ApplicationFrame   상속 받아서 사용할때
super() 호출할때 java.awt.HeadlessException  오류 발생함

구글링에서 해결 관련 사항이 많이나오지만 해결은 안됨

- http://cewolf.sourceforge.net/new/faq/faq.html#Troubleshooting0

- Djava.awt.headless=true , 기타 x-window 기동~~
   DISPLAY~어쩌구~등

결론은 linux에서 ApplicationFrame 상속받지 않고 사용 하면된다. ~.~


http://www.java2s.com/Code/Java/Chart/Line-Chart.htm


 

:
Posted by mastar


suite.tistory.com 2009 07  fs

뭐~ 기간구하기 가입 총기간 개월 , 년도 같은거 구할때

먼저 시작날짜 하고 종료 날짜를 GregorianCalendar 에 세팅

시작 GregorianCalendar s_cal= new GregorianCalendar(strtYear,strtMonth,startDay);
종료 GregorianCalendar e_cal= new GregorianCalendar(endYear,endMonth+1,endDay);


다음 밀리세컨드로 빼서 계산

 Long mdiff=( e_cal.getTimeInMillis() - s_cal.getTimeInMillis() ) / 60000 / 60 / 24 ;

System.out.println("경과월 : " + mdiff);
System.out.println("경과년 : " + mdiff / 365 );

이상 끝~~


 

:
Posted by mastar

2008 08 fs ~ http://suite.tistory.com/

windows 오라클 10G 에서`~~ 테스트

Connection.setAutoCommit(false) < -  commit 을 내가 함~~지정하고

insert , delete 후
executeUpdate() 실행 다음
commit() 하지 안했는데  그냥 입력 처리가 된다 ~.~

살짝 테스트를 해보니

소스에서  Connection.close()
            => close()를 해줘서 그랬다~~  이유 관심 없음 ~.~

setAutoCommit(false) 로 하고 commit 안해줘도 들어 갈수 있으니 조금 주의?를 해야겠다~~
어쨌든 소스에는

setAutoCommit(false)
executeUpdate()
commit()

예외 상황 없이 실행되는 finally에 ~
close()



다해주자~~~ commit()에서 에러나면 예외로 갈테니~~




:
Posted by mastar