자바에서 Process 와 Runtime.getRuntime().exec()를 이용한 외부 프로그램 실행시..
특정디렉토리에서 수행되도록 하는 경우.
주의할 점은 명령실행 후 출력되는 내용이 getInputStream()으로 대부분 나오지만,
간혹 getErrorStream() 으로 내보내지는 경우도 있으니, 둘다 확인해봐야 한다.
public class Test {
public static void main( String[] args ) {
try {
Process child = Runtime.getRuntime().exec( "java -version", null, new File( "D:\\Java\\jdk1.6.0_16\\bin\\" ) );
System.out.println( readAll( child ) );
child.waitFor();
System.out.println( child.exitValue() );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
private static String readAll( Process child ) {
StringBuffer sb = new StringBuffer();
sb.append( read( child.getInputStream() ) ).append( "\n" );
sb.append( read( child.getErrorStream() ) );
/**
* (필수) OutputStream 을 닫는다.
* waitFor() 무한대기 방지를 위해
*/
try {
child.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString().trim();
}
private static String read( InputStream in ) {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
String line = null;
br = new BufferedReader( new InputStreamReader( in ));
while ( ( line = br.readLine() ) != null ) {
sb.append( line ).append( "\n" );
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
/**
* (필수) InputStream 을 닫는다.
* waitFor() 무한대기 방지를 위해
*/
try {
if ( br != null ) br.close ( );
} catch (IOException e) {
e.printStackTrace();
}
}
// 문자열의 앞/뒤 공백을 제거하고 담는다.
return Util.emptyString( sb.toString() ).trim();
}
}
2012년 9월 12일 수요일
2012년 6월 20일 수요일
SCALABLE VECTOR GRAPHICS (SVG) 샘플 코드
SVG ?
http://www.w3.org/Graphics/SVG/
SVG 를 활용하는 간단한 샘플코드.
package image;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import javax.media.jai.Interpolation;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.operator.ScaleDescriptor;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
public class SVGUtil {
public static void imgToSvg(String imgPath, String svgPath, int destWidth, int destHeight) throws Exception{
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
ParameterBlock pb = new ParameterBlock();
pb.add(imgPath);
PlanarImage image = JAI.create("fileload", pb);
float xScale = (float) destWidth / image.getWidth();
float yScale = (float) destHeight / image.getHeight();
PlanarImage renderedOp = ScaleDescriptor.create(image, new Float(xScale), new Float(yScale), new Float(0.0f), new Float(0.0f), Interpolation.getInstance(Interpolation.INTERP_BICUBIC), null);
svgGenerator.drawImage(renderedOp.getAsBufferedImage(), 0, 0,renderedOp.getAsBufferedImage().getWidth(), renderedOp.getAsBufferedImage().getHeight(), null);
svgGenerator.dispose();
Writer out = new OutputStreamWriter(new FileOutputStream(new File(svgPath)), "UTF-8");
svgGenerator.stream(out, false);
out.flush();
out.close();
}
public static void main(String[] args) {
try {
long start = System.currentTimeMillis();
ClassLoader cl;
cl = Thread.currentThread().getContextClassLoader();
if( cl == null )
cl = ClassLoader.getSystemClassLoader();
URL defaultPath = cl.getResource( "" );
imgToSvg(defaultPath.getPath() + "test.jpg" , defaultPath.getPath() +"test.svg", 320, 280);
long end = System.currentTimeMillis();
long elapsed = end - start;
System.out.print( "-----> " + ((double)elapsed / 1000.0) );
} catch(Exception e) {
e.printStackTrace();
}
}
}
http://www.w3.org/Graphics/SVG/
SVG 를 활용하는 간단한 샘플코드.
package image;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import javax.media.jai.Interpolation;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.operator.ScaleDescriptor;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
public class SVGUtil {
public static void imgToSvg(String imgPath, String svgPath, int destWidth, int destHeight) throws Exception{
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
ParameterBlock pb = new ParameterBlock();
pb.add(imgPath);
PlanarImage image = JAI.create("fileload", pb);
float xScale = (float) destWidth / image.getWidth();
float yScale = (float) destHeight / image.getHeight();
PlanarImage renderedOp = ScaleDescriptor.create(image, new Float(xScale), new Float(yScale), new Float(0.0f), new Float(0.0f), Interpolation.getInstance(Interpolation.INTERP_BICUBIC), null);
svgGenerator.drawImage(renderedOp.getAsBufferedImage(), 0, 0,renderedOp.getAsBufferedImage().getWidth(), renderedOp.getAsBufferedImage().getHeight(), null);
svgGenerator.dispose();
Writer out = new OutputStreamWriter(new FileOutputStream(new File(svgPath)), "UTF-8");
svgGenerator.stream(out, false);
out.flush();
out.close();
}
public static void main(String[] args) {
try {
long start = System.currentTimeMillis();
ClassLoader cl;
cl = Thread.currentThread().getContextClassLoader();
if( cl == null )
cl = ClassLoader.getSystemClassLoader();
URL defaultPath = cl.getResource( "" );
imgToSvg(defaultPath.getPath() + "test.jpg" , defaultPath.getPath() +"test.svg", 320, 280);
long end = System.currentTimeMillis();
long elapsed = end - start;
System.out.print( "-----> " + ((double)elapsed / 1000.0) );
} catch(Exception e) {
e.printStackTrace();
}
}
}
2012년 2월 14일 화요일
JAVA CLOSE_WAIT 관련 내용
JAVA CLOSE_WAIT 이슈는 자바의 버그에서 비롯된 것으로 판단됨.
관련 버그 내용.
bug: 6215050 java classes_nio (so) SocketChannel created in CLOSE_WAIT and never cleaned up.. File Descriptor leak
http://www.oracle.com/technetwork/java/javase/releasenotes-142123.html
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6215050
이와 관련한 내용 및 문제제기 관련 사이트 (해결방법은 아니므로 참고만 하세요.)
http://stackoverflow.com/questions/8326058/how-to-kill-tcp-connection-with-close-wait-state
https://forums.oracle.com/forums/thread.jspa?threadID=1160014
http://tux.hk/index.php?m=05&y=09&entry=entry090521-111844
http://www.thatisjava.com/java-core-apis/35975/
2011년 6월 16일 목요일
버퍼사이즈가 읽기/쓰기 성능에 미치는 영향
버퍼사이즈가 읽기/쓰기 성능에 미치는 영향
파일을 읽고 쓸때, 한번에 읽어들이는 데이터의 크기에 따라 읽기/쓰기 성능이 달라진다는 것은 상식선에서 알고 있을 것이다. 대략 알고 있는 바로는 1024 바이트 단위로 읽어올 때 가장 효과적인 것으로 알고 있다. 실제, 이러한 우리의 상식이 올바른지를 확인하기 위해서 버퍼 크기에 따른 읽기/쓰기 성능에 대한 자료를 만들어보기로 했다.
.. 이하 생략 ( 아래 원문 참고 )
http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/system_programing/File/buffer_size_perf
파일을 읽고 쓸때, 한번에 읽어들이는 데이터의 크기에 따라 읽기/쓰기 성능이 달라진다는 것은 상식선에서 알고 있을 것이다. 대략 알고 있는 바로는 1024 바이트 단위로 읽어올 때 가장 효과적인 것으로 알고 있다. 실제, 이러한 우리의 상식이 올바른지를 확인하기 위해서 버퍼 크기에 따른 읽기/쓰기 성능에 대한 자료를 만들어보기로 했다.
.. 이하 생략 ( 아래 원문 참고 )
http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/system_programing/File/buffer_size_perf
2011년 5월 18일 수요일
[MSSQL] SQL2005용 JDBC 드라이버 관련
기존버전 : jdbc:microsoft:sqlserver://111.222.111.111:1433;databasename=ABCD
신규버전 : jdbc:sqlserver://111.222.111.111:1433;databasename=ABCD
중간에 microsoft 가 빠졌음..주의
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://111.222.111.111:1433;databasename=ABCD;user=userid;password=pw";
// Declare the JDBC objects.
Connection con = null;
CallableStatement cstmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
//cstmt = con.prepareCall("{call spBoardDataList(?,?,?,?,?,?)}");
cstmt = con.prepareCall("spBoardDataList '0120','','',1,9,0");
// cstmt.setString(1, "0120");
// cstmt.setString(2, "");
// cstmt.setString(3, "");
// cstmt.setInt(4, 1);
// cstmt.setInt(5, 9);
// cstmt.setInt(6, 0);
rs = cstmt.executeQuery();
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (cstmt != null) try { cstmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
신규버전 : jdbc:sqlserver://111.222.111.111:1433;databasename=ABCD
중간에 microsoft 가 빠졌음..주의
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://111.222.111.111:1433;databasename=ABCD;user=userid;password=pw";
// Declare the JDBC objects.
Connection con = null;
CallableStatement cstmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
//cstmt = con.prepareCall("{call spBoardDataList(?,?,?,?,?,?)}");
cstmt = con.prepareCall("spBoardDataList '0120','','',1,9,0");
// cstmt.setString(1, "0120");
// cstmt.setString(2, "");
// cstmt.setString(3, "");
// cstmt.setInt(4, 1);
// cstmt.setInt(5, 9);
// cstmt.setInt(6, 0);
rs = cstmt.executeQuery();
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (cstmt != null) try { cstmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
라벨:
Java,
JDBC,
JDBCDriver,
MSSQL,
SQL2005
[JAVA] IP또는 도메인으로 해당서버의 국가 얻어오기
IP또는 도메인으로 해당서버의 국가 얻어오기 | ☞ Programming Study
2007.12.26 20:40
younjoo0304 카페 스탭
http://cafe.naver.com/worldssims/78372
가끔 특정 IP도는 도메인이 어느 국가에서 서비스 되고 있는지 궁금할때가 있다..
역시 누군가 이런걸 알아내는 라이브러리를 만들어 놓았다.
다음을 방문하여 받아보시라.
http://sourceforge.net/projects/javainetlocator/
사용법은 대충 다음과 같다.
import java.util.Locale;
import net.sf.javainetlocator.InetAddressLocator;
import net.sf.javainetlocator.InetAddressLocatorException;
public class InetAddressLocatorTest {
public static void main(String[] args){
try {
Locale locale = InetAddressLocator.getLocale("pistos.pe.kr"); // 딸랑 이거 한줄!
System.out.println(locale.getCountry());
} catch (InetAddressLocatorException e) {
e.printStackTrace();
}
}
}
더이상 심플할 수 없다.. 반환된 Locale 객체를 가지고 해당 IP 또는 도메인이 위치한 국가의 정보를 알아낼 수 있다.
보너스로 국가코드별 국기를 누군가가 gif와 ico 파일로 만들어놓은게 있다..
둘이 같이 쓰면 이쁠것이다.
2007.12.26 20:40
younjoo0304 카페 스탭
http://cafe.naver.com/worldssims/78372
가끔 특정 IP도는 도메인이 어느 국가에서 서비스 되고 있는지 궁금할때가 있다..
역시 누군가 이런걸 알아내는 라이브러리를 만들어 놓았다.
다음을 방문하여 받아보시라.
http://sourceforge.net/projects/javainetlocator/
사용법은 대충 다음과 같다.
import java.util.Locale;
import net.sf.javainetlocator.InetAddressLocator;
import net.sf.javainetlocator.InetAddressLocatorException;
public class InetAddressLocatorTest {
public static void main(String[] args){
try {
Locale locale = InetAddressLocator.getLocale("pistos.pe.kr"); // 딸랑 이거 한줄!
System.out.println(locale.getCountry());
} catch (InetAddressLocatorException e) {
e.printStackTrace();
}
}
}
더이상 심플할 수 없다.. 반환된 Locale 객체를 가지고 해당 IP 또는 도메인이 위치한 국가의 정보를 알아낼 수 있다.
보너스로 국가코드별 국기를 누군가가 gif와 ico 파일로 만들어놓은게 있다..
둘이 같이 쓰면 이쁠것이다.
[Java] MacAddress 갖고 오기 (JDK 6.0)
http://suein1209.tistory.com/373?srchid=BR1http%3A%2F%2Fsuein1209.tistory.com%2F373 MacAddress 갖고 오기 (JDK 6.0) 자바철학/자바 2009/09/01 17:56 자바 에서 맥 주소를 갖고 와야 할때가 있다... ㅋㅋ 그때 사용 하기~ 이건 JDK 6.0 부터 추가된 사항이다. import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class NetworkInterfaceTest { public static void main(String[] args) throws SocketException { Enumeration<NetworkInterface> nienum = NetworkInterface.getNetworkInterfaces(); while (nienum.hasMoreElements()) { NetworkInterface ni = nienum.nextElement(); System.out.print(ni.getName()); System.out.print(" : "); byte[] hardwareAddress = ni.getHardwareAddress(); String div = ""; if (hardwareAddress != null) { for (byte b : hardwareAddress) { System.out.print(div); System.out.format("%02X", b); div = "-"; } } System.out.println(); } } } |
라벨:
맥어드레스,
자바,
Java,
JDK6.0,
MacAddress
[Java] NetworkInterface를 이용한 IP추출
InetAddress.getLocalHost() vs Socket.getLocalAddress() 를 이용하면.. Windows에서는 정상적으로 IP가 출력되지만, Linux에서는 127.0.0.1 이 출력된다. 이는 /etc/hosts 에 설정된 값이 127.0.0.1 ==> localhost 로 되어있는 경우인데, 이 hosts 파일을 수정하지 않으면, 계속 127.0.0.1 만 출력된다. 아래 소스에서는 NetworkInreface를 이용하여.. 이더넷설정중 eth0 의 IP를 꺼내는 방법을 소개하고있다. -------------------------------------------------------------- import java.net.*; import java.util.*; public class GetPublicHostname{ public static void main(String[] args) throws Throwable{ NetworkInterface iface = null; for(Enumeration ifaces = NetworkInterface.getNetworkInterfaces();ifaces.hasMoreElements();){ iface = (NetworkInterface)ifaces.nextElement(); System.out.println("Interface:"+ iface.getDisplayName()); InetAddress ia = null; for(Enumeration ips = iface.getInetAddresses();ips.hasMoreElements();){ ia = (InetAddress)ips.nextElement(); System.out.println(ia.getCanonicalHostName()+" "+ ia.getHostAddress()); } } } } 출처: http://www.jguru.com/faq/view.jsp?EID=790132 |
[JAVA] 대소문자 관계없이 검색어 찾아 강조문구로 바꾸기..
| [JAVA] 대소문자 관계없이 검색어 찾아 강조문구로 바꾸기.. // 검색시 대소문자 관계없이 강조문구로 바꾸기... public String convertWords(String oriString, String findword) { // replaceAll ==> 버그 있음.. 검색어 [강풀] ==> 결과 : [강풀][강풀] 일케 두번 나온다.. StringBuffer newString = new StringBuffer(oriString); StringBuffer tmpText = new StringBuffer(oriString.toUpperCase()); // 임시로 사용할 원본의 대문자.. String newText = oriString.toUpperCase(); // 원문의 복사본을 대문자로 바꾸기.. findword = findword.toUpperCase(); // 검색어도 대문자로.. newText = newText.replaceAll(findword, "<font color=red>" + findword + "</font>"); // 일단 복사본을 원하는 강조문구로 바꾸어 놓는다.. int leng = newText.length() - 1; for (int i = 0; i < leng; i ++ ) { char chr = newText.charAt(i); try { if (chr != tmpText.charAt(i)) // 강조문구 적용부분을 찾는다... { tmpText.insert(i, chr); // 길이를 맞추기위해 여기에도 삽입한다. newString.insert(i, chr); // 원문에 강조문구를 삽입한다.. } } catch (Exception ee) // 맨뒤쪽에 강조문구가 들어가는경우 길이차이로 String index out of range 발생.. { tmpText.append(chr); newString.append(chr); } } return newString.toString(); } ===> 제목, 내용에 적용하면 좋을 듯...냐하하.. |
[JAVA] RandomAccessFile 을 사용한 파일 엑세스
/* * 파일에 기록하기 세번째 * 파일 전체를 다시쓰지 않고 덧붙이는 경우에 사용한다. */ public void setEvent3(String filename, String str) { try { RandomAccessFile rFile = new RandomAccessFile(filename,"rw"); //r, w, rw rFile.seek(rFile.length()); rFile.write(str.getBytes()); rFile.close(); } catch (IOException e) { e.printStackTrace(); } } 랜덤엑세스파일을 사용하면 원하는 부분에 추가/삭제를 할 수 있다..!!! |
[JAVA] JAI 와 JIU를 혼용하여 이미지를 빠르고 품질높게 크기 변환하기
오호... 이것땜에 한참 고생했네..
이미지 로딩부분은 JAI 를 사용하고..
변환은 java 의 그래픽기능을 이용하고
저장은 JIU 를 이용한다.
/**
* filename : Test.java
* package : ewha.say.server.image
* comment :
* author : cozysoul
* date : 2007. 11. 27
*/
package ewha.say.server.image;
import ewha.say.server.util.ImageUtil;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import net.sourceforge.jiu.codecs.CodecMode;
import net.sourceforge.jiu.codecs.ImageCodec;
import net.sourceforge.jiu.codecs.PNGCodec;
import net.sourceforge.jiu.data.PixelImage;
import net.sourceforge.jiu.gui.awt.BufferedRGB24Image;
public class Test {
public static void main(String[] args) {
long sTime = System.currentTimeMillis();
new Test().pngReduceOriScale("E:/Backup/kim.jpg", "E:/Backup/kim.png", 232, 192);
long eTime = System.currentTimeMillis();
System.out.println("-->" + (eTime - sTime));
sTime = System.currentTimeMillis();
new Test().pngReduceOriScale("E:/Backup/flower.jpg", "E:/Backup/flower.png", 232, 192);
eTime = System.currentTimeMillis();
System.out.println("-->" + (eTime - sTime));
}
/**
* 원본이미지를 지정된 사이즈로 스케일에 맞게 변환한다.
* JAI 와 JIU를 혼용하여 속도를 빠르고 품질을 올려 변환수행
* @param oriFile 원본파일경로
* @param newFile 생성될 파일경로
* @param width width 최대크기
* @param height height 최대크기
* @return 변환여부
*/
public boolean pngReduceOriScale(String oriFile, String newFile, int width, int height) {
boolean result = true;
try {
//이미지 로드
RenderedOp image = JAI.create("fileload", oriFile);
BufferedImage tmp = image.getAsBufferedImage();
//스케일 된 이미지 만들기---------------------------------------------------------
int[] scale = ImageUtil.getScale(width, height, tmp.getWidth(), tmp.getHeight());
Image scaleimage = tmp.getScaledInstance(scale[0], scale[1], 4); // 1:DEFAULT/기본, 2:FAST/성능, 4:SMOOTH/품질
// 생성될 파일의 용량을 고려하여 15bit 로 읽어들여 변환한다.
BufferedImage png24 = ImageUtil.toBufferedImageHints(scaleimage, scale[0], scale[1], BufferedImage.TYPE_USHORT_555_RGB);
PixelImage pi = new BufferedRGB24Image(png24).createCopy();
// PNG 변환 & 파일로 저장
BufferedOutputStream out = new BufferedOutputStream(new ByteArrayOutputStream());
ImageCodec codec = new PNGCodec();
codec.setOutputStream(out);
codec.setImage(pi);
codec.setBounds(0, 0, scale[0] - 1, scale[1] - 1); // 지정하지 않으면 내부적으로 자동지정되어 시간 더 걸림
codec.setFile(newFile, CodecMode.SAVE);
codec.process();
codec.close();
out.close();
}
catch (Exception e) {
result = false;
}
return result;
}
}
public static BufferedImage toBufferedImageHints(Image image, int width, int height, int mode)
{
RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
qualityHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
BufferedImage bufferedImage = new BufferedImage(width, height, mode);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setRenderingHints(qualityHints);
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return bufferedImage;
}
피드 구독하기:
글 (Atom)