Contents
- 1 Official Tutorial
- 2 멋진 링크
- 3 ibm's eclipse
- 4 JavaOS - JNode
- 5 java file io
- 6 java 로 MD5 구하기
- 7 jdbc
- 8 Swing
- 8.1 JFrame 이 닫힐 때 프로그램 종료하기
- 8.2 MessageBox 띄우기
- 8.3 checkbox 쓰기
- 9 Eclipse & SWT
- 9.1 Swing 과 AWT 의 차이
- 9.2 Web Browser
- 10 Game Programming
- 10.1 전체 화면 만들기
- 11 Java WebStart
- 12 Data Type Converting
- 13 기타
- 13.1 JRE Auto Install
- 13.2 특정 url 의 파일 받아오기
- 13.3 html 파일에서 각종 tag 없애기
- 13.4 java 에서 클립보드의 문자열 받아오기
- 13.5 java 에서 mp3 play
- 13.6 JFree Software
- 13.7 Native Code 로 컴파일하기
- 13.8 JScrollPane 밑의 JTextarea 에서 스크롤바가 작동을 안 할 때
- 13.9 javaWebStart 없는데 알아서 설치하기 html version
- 13.10 java 에서 shell 명령 내리기
- 14 기타
- 14.1 자바로 시리얼 통신하기
- 14.2 jar 파일에 대해서
- 14.3 Converting Flash Movies to MIDlets
- 14.4 JWS 를 이용한 JRE 설치하기
5 java file io #
public static void main(String[] args)
{
FileReader reader;
try
{
reader = new FileReader("temp.txt");
char[] buffer = new char[256];
int i = 0;
i = reader.read(buffer, 0, 256);
if (0 == i)
{
System.out.println("Can't read the file");
}
else
{
String k = new String(buffer);
k = k.substring(0, i);
System.out.println(k);
StringBuffer hexString = new StringBuffer();
try
{
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(k.getBytes());
byte[] digest = algorithm.digest();
for (i = 0; i < digest.length; i++)
{
hexString.append(Integer.toHexString(0xff & digest[i]));
}
}
catch (Exception ex)
{
ex.printStackTrace();
//return "";
}
k = hexString.toString();
FileWriter writer = new FileWriter("output.txt");
writer.write(k);
writer.close();
}
reader.close();
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
}
6 java 로 MD5 구하기 #
public static String getMD5SUM(final String strOriginal)
{
StringBuffer hexString = new StringBuffer();
try
{
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(strOriginal.getBytes());
byte[] digest = algorithm.digest();
for(int i=0; i< digest.length; i++)
{
hexString.append(Integer.toHexString(0xff & digest[i]));
}
}
catch(Exception ex)
{
ex.printStackTrace();
//return "";
}
return hexString.toString();
}
7 jdbc #
/** The constructor expects the naming server URL and the context provider class.
* For example, the sample URL for ldap server on localhost can be
* ldap://localhost:389/ou=jdbc,cn=manager,dc=microsoft,dc=com,
* and the provider class name can be com.sun.jndi.ldap.LdapCtxFactory
*/
import com.microsoft.jdbcx.sqlserver.SQLServerDataSource;
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;
import javax.sql.*;
import java.sql.*;
public class JNDISetup
{
Context ctx = null;
String url;
String factory;
JNDISetup(String url, String factory){
this.url=url;
this.factory=factory;
getContext();
}
private void getContext(){
try{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
env.put(Context.PROVIDER_URL, url);
ctx = new InitialContext(env);
}catch(Exception e){
System.out.println("Error in SetupJNDI:getContext() "+e.getMessage());
e.printStackTrace();
}
}
public boolean bindDataSource(String bindName)
{
boolean isRegistered =false;
try
{
SQLServerDataSource mds = new SQLServerDataSource();
mds.setDescription("MS SQLServerDataSource");
mds.setServerName("sqlserver");
mds.setPortNumber(1433);
mds.setDatabaseName("pubs");
mds.setSelectMethod("cursor");
ctx.rebind(bindName, mds);
System.out.println("Bind success");
isRegistered=true;
}
catch(Exception e)
{
System.out.println("Error Occured in JNDISetup: " + e.getMessage());
e.printStackTrace();
}
return isRegistered;
}
public javax.sql.ConnectionPoolDataSource getDataSource(String bindName){
javax.sql.ConnectionPoolDataSource ds = null;
try{
ds = (javax.sql.ConnectionPoolDataSource) ctx.lookup(bindName);
}catch(Exception e){
System.out.println("Error in JNDISetup:getDataSource() : "+e.getMessage());
e.printStackTrace();
}
return ds;
}
}
import java.*;
public class Connect{
private java.sql.Connection con = null;
private final String url = "jdbc:microsoft:sqlserver://";
private final String serverName= "localhost";
private final String portNumber = "1433";
private final String databaseName= "pubs";
private final String userName = "user";
private final String password = "password";
// Informs the driver to use server a side-cursor,
// which permits more than one active statement
// on a connection.
private final String selectMethod = "cursor";
// Constructor
public Connect(){}
private String getConnectionUrl(){
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection(){
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties(){
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{
con= this.getConnection();
if(con!=null){
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("tDriver Name: "+ dm.getDriverName());
System.out.println("tDriver Version: "+ dm.getDriverVersion ());
System.out.println("nDatabase Information ");
System.out.println("tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next()){
System.out.println("tcatalog: "+ rs.getString(1));
}
rs.close();
rs = null;
closeConnection();
}else System.out.println("Error: No active Connection");
}catch(Exception e){
e.printStackTrace();
}
dm=null;
}
private void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
Connect myDbTest = new Connect();
myDbTest.displayDbProperties();
}
}
/*
이 코드가 성공적으로 실행되면 다음과 비슷하게 출력됩니다.
Connection Successful!
Driver Information
Driver Name: SQLServer
Driver Version: 2.2.0022
Database Information
Database Name: Microsoft SQL Server
Database Version: Microsoft SQL Server 2000 - 8.00.384 (Intel X86)
May 23 2001 00:02:52
Copyright (c) 1988-2000 Microsoft Corporation
Desktop Engine on Windows NT 5.1 (Build 2600: )
Avalilable Catalogs
catalog: master
catalog: msdb
catalog: pubs
catalog: tempdb
*/
8.1 JFrame 이 닫힐 때 프로그램 종료하기 #
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
8.2 MessageBox 띄우기 #
JOptionPane.showMessageDialog(this, "Hello");
8.3 checkbox 쓰기 #
public void itemStateChanged(java.awt.event.ItemEvent e)
{
m_frame.setAlwaysOnTop(e.getStateChange() == ItemEvent.SELECTED);
}
9.1 Swing 과 AWT 의 차이 #
AWT 와 SWT 의 차이점..(이클립스는 SWT임)
awt 는 선에서 모든 OS 의 공통된 UI 들에만 접근하도록 사용했고(즉 OS 가 지원하는 UI들의 공집합만 지원.. 그래서 윈도우에는 존재하는 트리나 테이블이 솔라리스의 모티브에서 지원되지 않기에 뺌)
SWT 는 IBM 에서 그동안 AWT 의 문제점으로 지적된 부분을 개선하기 위해..(UI의 단순함과 트리나 테이블등이 지원안되는 문제 등..) AWT 와 같이 지원하는 OS 의 peer 는 그대로 이용하되 만약 해당 OS 에서 지원되지 않는다면 스윙처럼 직접 그려서 쓰는 것이죠.
9.2 Web Browser #
/*
* Created on 2004. 4. 17.
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
/**
* @author zelon
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.browser.*;
public class Browser01 {
public static void amain(String [] args) {
// public static void main(String [] args) {
Display display = new Display();
final Shell shell = new Shell(display);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
shell.setLayout(gridLayout);
ToolBar toolbar = new ToolBar(shell, SWT.NONE);
ToolItem itemBack = new ToolItem(toolbar, SWT.PUSH);
itemBack.setText("Back");
ToolItem itemForward = new ToolItem(toolbar, SWT.PUSH);
itemForward.setText("Forward");
ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
itemStop.setText("Stop");
ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
itemRefresh.setText("Refresh");
ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
itemGo.setText("Go");
GridData data = new GridData();
data.horizontalSpan = 3;
toolbar.setLayoutData(data);
Label labelAddress = new Label(shell, SWT.NONE);
labelAddress.setText("Address");
final Text location = new Text(shell, SWT.BORDER);
data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.horizontalSpan = 2;
data.grabExcessHorizontalSpace = true;
location.setLayoutData(data);
final Browser browser = new Browser(shell, SWT.NONE);
data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.verticalAlignment = GridData.FILL;
data.horizontalSpan = 3;
data.grabExcessHorizontalSpace = true;
data.grabExcessVerticalSpace = true;
browser.setLayoutData(data);
final Label status = new Label(shell, SWT.NONE);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
status.setLayoutData(data);
final ProgressBar progressBar = new ProgressBar(shell, SWT.NONE);
data = new GridData();
data.horizontalAlignment = GridData.END;
progressBar.setLayoutData(data);
/* event handling */
Listener listener = new Listener() {
public void handleEvent(Event event) {
ToolItem item = (ToolItem)event.widget;
String string = item.getText();
if (string.equals("Back")) browser.back();
else if (string.equals("Forward")) browser.forward();
else if (string.equals("Stop")) browser.stop();
else if (string.equals("Refresh")) browser.refresh();
else if (string.equals("Go")) browser.setUrl(location.getText());
}
};
browser.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
if (event.total == 0) return;
int ratio = event.current * 100 / event.total;
progressBar.setSelection(ratio);
}
public void completed(ProgressEvent event) {
progressBar.setSelection(0);
}
});
browser.addStatusTextListener(new StatusTextListener() {
public void changed(StatusTextEvent event) {
status.setText(event.text);
}
});
browser.addLocationListener(new LocationListener() {
public void changed(LocationEvent event) {
location.setText(event.location);
}
public void changing(LocationEvent event) {
}
});
itemBack.addListener(SWT.Selection, listener);
itemForward.addListener(SWT.Selection, listener);
itemStop.addListener(SWT.Selection, listener);
itemRefresh.addListener(SWT.Selection, listener);
itemGo.addListener(SWT.Selection, listener);
location.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(location.getText());
}
});
shell.open();
browser.setUrl("http://www.wimy.com");
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
아래는 가장 간단하게 보여주는 소스
/*
* Created on 2004. 6. 15.
*
*
*/
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.*;
/**
* @author Zelon
*
* 가장 간단한 브라우저를 띄우는 클래스
*
*/
public class ZBrowser
{
public void ShowBrowser()
{
Display display = new Display();
final Shell shell = new Shell(display);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
shell.setLayout(gridLayout);
Browser a = new Browser(shell, SWT.NONE);
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.verticalAlignment = GridData.FILL;
data.horizontalSpan = 3;
data.grabExcessHorizontalSpace = true;
data.grabExcessVerticalSpace = true;
a.setLayoutData(data);
a.setUrl("http://www.wimy.com");
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
}
org.eclipse.swt 를 찾지 못할 때는
Project -> Properties -> Java Build Path -> Libraries -> Add External JARs... 에서 eclipse 디렉토리의
plugins -> org.eclipse.swt.[platform].x.x.x.vxxxx.jar 을 선택해준다.
platform 은 윈도우의 경우 win32.win32, 리눅스의 경우 gtk.linux 이다.
실행시에
LinkError 가 나면, Debug 설정창에서 Arguments 에서 VM arguments 에 다음과 같이 추가한다.
-Djava.library.path={runtime-library-path}
ex)
-Djava.library.path="C:Program Fileseclipsepluginsorg.eclipse.swt.win32_3.0.0oswin32x86"
10.1 전체 화면 만들기 #
GraphicsDevice dev = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
GraphicsConfiguration gc = dev.getDefaultConfiguration();
DisplayMode mode = new DisplayMode(800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN);
JFrame frame = new JFrame(gc);
frame.setUndecorated(true);
frame.setIgnoreRepaint(true);
frame.show();
dev.setFullScreenWindow(frame);
if(dev.isDisplayChangeSupported()) dev.setDisplayMode(mode);
//frame.createBufferStrategy(numBuffers);
frame.createBufferStrategy(2);
BufferStrategy bufferStrategy = frame.getBufferStrategy();
11 Java WebStart #
자동으로 JWS 까는 html 코드
<html>
<body onload="loadYourApplication()">
<script language="JavaScript1.2">
function isJWSInstalled()
{
var javawsInstalled = 0;
isIE = "false";
if (navigator.mimeTypes && navigator.mimeTypes.length)
{
x = navigator.mimeTypes['application/x-java-jnlp-file'];
if (x) javawsInstalled = 1;
}
else
{
isIE = "true";
}
if(isIE == "true")
{
return VBisJWSInstalled();
}
else return javawsInstalled;
}
</script>
<SCRIPT LANGUAGE="VBScript">
FUNCTION VBisJWSInstalled()
on error resume next
If Not(IsObject(CreateObject("JavaWebStart.IsInstalled"))) Then
VBisJWSInstalled = 0
Else
VBisJWSInstalled = 1
End If
END FUNCTION
</SCRIPT>
<script language="JavaScript">
// this function checks the JWS installation and if yes then launches the application
function loadYourApplication()
{
if(isJWSInstalled() != 1)
{
if(window.confirm("Java Web Start is not installed on your computer. To run Your Application you need to install it. Do you want to proceed installing Java Web Start"))
{
// download the java web start installation exe from sun website. This contains the JRE also so you dont have to worry about that.
document.location.href ='http://aurl/jws.exe';
}
}
else
{
// call a URL which is actually a JNLP file. Java Web Start application is launched.
alert("ok");
}
}
</script>
</body>
</html>
12 Data Type Converting #
- byte[] -> String : new String(byte[])
- char[] -> String : String(static).copyValueOf()
13.2 특정 url 의 파일 받아오기 #
String GetHtmlSource(String strUrl)
{
String ret = "";
URL url;
try
{
url = new URL(strUrl);
URLConnection con = url.openConnection();
InputStream in = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while (( strLine = br.readLine())!= null)
{
ret += strLine;
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( IOException ex )
{
}
return ret;
}
13.3 html 파일에서 각종 tag 없애기 #
strOri = strOri.replaceAll("<.*?>","");
13.4 java 에서 클립보드의 문자열 받아오기 #
Clipboard clipboard = getToolkit().getSystemClipboard();
Transferable tf = clipboard.getContents(this);
if ( tf != null )
{
try
{
m_tfResult.setText((String)tf.getTransferData(DataFlavor.stringFlavor));
}
catch (UnsupportedFlavorException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
13.6 JFree Software #
| JFreeReport | 리포팅 라이브러리 |
| JFreeChart | 차트 그리는 라이브러리 |
| JCommon | 다양한 유틸리티 라이브러리 |
13.7 Native Code 로 컴파일하기 #
13.8 JScrollPane 밑의 JTextarea 에서 스크롤바가 작동을 안 할 때 #
JScrollPane 의
PreferredSize 를
JTextarea 의
PreferredSize 보다 작게 해본다 -_-;
13.9 javaWebStart 없는데 알아서 설치하기 html version #
<html>
<body onload="loadYourApplication()">
<script language="JavaScript1.2">
function isJWSInstalled()
{
var javawsInstalled = 0;
isIE = "false";
if (navigator.mimeTypes && navigator.mimeTypes.length)
{
x = navigator.mimeTypes['application/x-java-jnlp-file'];
if (x) javawsInstalled = 1;
}
else
{
isIE = "true";
}
if(isIE == "true")
{
return VBisJWSInstalled();
}
else return javawsInstalled;
}
</script>
<SCRIPT LANGUAGE="VBScript">
FUNCTION VBisJWSInstalled()
on error resume next
If Not(IsObject(CreateObject("JavaWebStart.IsInstalled"))) Then
VBisJWSInstalled = 0
Else
VBisJWSInstalled = 1
End If
END FUNCTION
</SCRIPT>
<script language="JavaScript">
// this function checks the JWS installation and if yes then launches the application
function loadYourApplication()
{
if(isJWSInstalled() != 1)
{
if(window.confirm("Java Web Start is not installed on your computer.
To run Your Application you need to install it.
Do you want to proceed installing Java Web Start"))
{
// download the java web start installation exe from sun website. This contains the JRE also so you dont have to worry about that.
document.location.href ='http://aurl/jws.exe';
}
}
else
{
// call a URL which is actually a JNLP file. Java Web Start application is launched.
alert("ok");
}
}
</script>
</body>
</html>
13.10 java 에서 shell 명령 내리기 #
결국 자바의 특성을 버리고 OS 에 의존적이 되겠지만... 분명 있어야할 종류의 클래스이다. Runtime 이라는 클래스를 이용.
import java.io.*;
class ExTelnet
{
public static void main(String[] args)
{
try
{
String [] cmd = {"cmd.exe","/c","start telnet oxen.konkuk.ac.kr"};
Process m ;
String S = "" ;
m = Runtime.getRuntime().exec(cmd) ;
BufferedReader in =
new BufferedReader(new InputStreamReader(
m.getInputStream()));
while((S=in.readLine()) != null)
{
System.out.println(S) ;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
14.3 Converting Flash Movies to MIDlets #
14.4 JWS 를 이용한 JRE 설치하기 #
안녕하세요..
java web start 를 사용해서 어플리케이션을 배포 하고 있습니다.
다름이 아니오라 사용자가 어플리케이션을 실행할때 jre 를 자동으로 다운로드 받게
하고 싶습니다. 물론 jre 설치가 안되어 있는 PC 상에서 말입니다.
지금은 1.4.2_04 버전을 사용하고 있습니다.
애플릿을 배포 할때 object 태그를 사용해서 jre 를 자동으로 다운 받드시
java web start 도 실행 할때 자동으로 다운 받고 하고 싶습니다.
경험 있으신 분의 조언 부탁 드립니다.
제목 : Re: 참고 URL 입니다.
글쓴이: 손님(guest) 2004/03/23 14:56:04 조회수:33 줄수:8
http://www.javastudy.co.kr/docs/okshin/JavaWebStart.htm#_Toc504213900
이곳은 위의 소스가 적용되어 있는곳입니다.
http://wilab.inha.ac.kr/ivj/