dbinfo.properties는  아래와같이

DBDRIVER=com.mysql.jdbc.Driver

DBURL=jdbc:mysql://아이피:3306/test

DBUSER=root

DBPWD=javamysql


//1. import하자.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Properties;


public class JdbcDemo {

//MySQL JDBC driver

private static final String DBDRIVER = "com.mysql.jdbc.Driver";

//MySQL Server jdbc-url --> jdbc:mysql://host_name(host_ip) : port_number/database_name

private static final String DBURL = "jdbc:mysql://172.16.46.134:3306/test";

//MySQL login user

private static final String DBUSER = "root";

//MySQL login password

private static final String DBPWD = "javamysql";

public static void main(String[] args) {

//2. Driver loading

try {

//Class.forName(DBDRIVER);

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

System.out.println("Driver loading Success");

//} catch (ClassNotFoundException e) {

}catch(SQLException ex){

System.out.println("Class Not Found");

}

//3. Database Connection

Connection conn = null;

try{

Properties info = new Properties();

info.setProperty("user", "root");

info.setProperty("password", "javamysql");

conn = DriverManager.getConnection(DBURL, info);

//conn = DriverManager.getConnection(DBURL, DBUSER, DBPWD);

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

//4. Statement 객체 생성

Statement stmt = null;

ResultSet rs = null;

try{

stmt = conn.createStatement();

//5. SQL Statement 생성 및 실행

String sql = "SELECT zipcode, sido, gugun, dong, bunji " +

                   "FROM zipcode " +

           "WHERE dong LIKE '%상하%'    ";

//1) 만일 SQL 문장이 SELECT --> executeQuery()

//2) 나머지 SQL 문장일 때(CREATE, UPDATE, INSERT, DELETE, GRANT, REVOKE,

            //                DROP, ALTER, COMMIT, ROLLBACK ...) --> executeUpdate()

rs = stmt.executeQuery(sql);

//6. ResultSet 실행

//ResultSet 을 열면 Cursor 가 첫번째 레코드 바로 위에 위치한다.

//next()는 다음 레코드를 읽는 역할을 하며, 반드시 정방향으로 진행

//만일 역방향(previous())를 사용하려면 Scrollable ResultSet 을 생성해야 함.

//나중에 배움....

if(!rs.next()){

System.out.println("찾을 수 없습니다.");

}

do{  

//만일 VARCHAR, CHAR ---> getString()

//만일 INT, INTEGER, NUMBER --> getInt()

//만일 REAL, NUMERIC, NUMBER(10,2) --> getDouble()

//만일 DATE, DATETIME --> getDate()

//getString(1) <-- 필드인덱스는 실제 테이블의 순서와 아무 상관이 없고,

//SELECT 1, 2, 3, 4, 5 -> SELECT 문장에서의 순서, 반드시 1부터 시작함.

String zipcode = rs.getString(1) ;

String sido = rs.getString("sido");

String gugun = rs.getString("gugun");

String dong = rs.getString(4);

String bunji = rs.getString(5);   if(bunji == null) bunji = "";

System.out.printf("(%s) %s %s %s %s\n", 

                       zipcode, sido, gugun, dong, bunji);

}while(rs.next());

}catch(SQLException ex){

ex.printStackTrace();

}

//7. Close 및 자원반납

try{

if(rs != null) rs.close();

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){}

}

}









import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Scanner;



public class JdbcDemo1 {

public static void main(String[] args) {

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

Scanner scan = new Scanner(System.in);

System.out.print("찾고자 하시는 동이름 : ");

String dongName = scan.nextLine();

//scan.nextLine();  //enter 날리자.

//Statement stmt = null;  

PreparedStatement pstmt = null;

String sql= "SELECT zipcode, sido, gugun, dong, bunji " + 

                  "FROM zipcode " + 

          "WHERE dong = ?";

ResultSet rs = null;

try{

pstmt = conn.prepareStatement(sql); //step 4.

pstmt.setString(1, dongName);    //---> 완전한 SQL 문장 형성

rs = pstmt.executeQuery();

if(!rs.next()){

System.out.println("찾을 수 없습니다.");  return;

}

do{  

String zipcode = rs.getString(1) ;

String sido = rs.getString("sido");

String gugun = rs.getString("gugun");

String dong = rs.getString(4);

String bunji = rs.getString(5);   if(bunji == null) bunji = "";

System.out.printf("(%s) %s %s %s %s\n", 

                       zipcode, sido, gugun, dong, bunji);

}while(rs.next());

rs.close();

pstmt.close();

}catch(SQLException ex){

ex.printStackTrace();

}

DBClose.close(conn);

}

}





import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

String user = info.getProperty("DBUSER");

String password = info.getProperty("DBPWD");

try{

conn = java.sql.DriverManager.getConnection(url, user, password);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}





import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;



public class DBClose {

public static void close(Connection conn){

try{

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

public static void close(Connection conn, Statement stmt){

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

public static void close(Connection conn, Statement stmt, ResultSet rs){

try{

if(rs != null) rs.close();

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

}


결론 무엇을 배웠을까


SQLite

http://www.sqlite.org/ 접속. Download 탭에가서, 윈도우즈 용인 Precompiled Binaries for Windows 에서 sqlite-shell-win32-x86-3080403.zip(289.42 KiB)  다운.

압축풀고, C:에 SqliteRoom을 만들고 압축푼, sqlite3.exe를 넣음.

커맨드창에가서 SqliteRoom으로 이동해서 sqlite3 하면 sqlite가 실행됨.   .quit하면 종료.

sqlite3 test.db 입력하면 아직 test.db가 만들어진게 아니라, 테이블을 하나만들면 test.db가 만들어짐.

어제와 같은 것을 만들어보면

CREATE TABLE helloworld 엔터

(

id integer primary key,

pwd varchar(20) NOT NULL

);

을 입력한다.

.schema helloworld 를 입력하면 방금 입력한 소스를 다보여준다.

INSERT INTO helloworld VALUES(1, '1234');

INSERT INTO helloworld(pwd) VALUES('3333');

INSERT INTO helloworld(pwd) VALUES('P@$$WOrd'); 

//아이디는 자동으로 1씩 증가하기 때문에 주지않아도된다.

.show를 치면 현재 sqlite의 세팅된 환경설정을 보여준다.

.mode column 을 쳐서 모드를 바꾸고

.headers on  을 쳐서 세팅바꾸면.

그리고 select * from helloworld; 를 치면 보기 편하게 바뀐것을 볼 수 있다.

.quit로 빠져나온다.

구글에서 sqlite database browser 를 쳐서 가장 위에 사이트에 들어가서 녹색 다운로드 버튼 클릭.

다운받은 것을 알집을 풀고 폴더의 이름을 Sqlite Database Browser 로 이름을 바꾼다. 폴더를 C:\ProgramFiles 에 넣는다.

그리고 SQLite Database Browser 를 실행시키고 아까 만든 test.db를 오픈하면 내용을 볼 수 있음. 장점은 커맨드명령을 싫어한는 사람을 위한.


이클립스 sql explorer - new profile 에가서 설정.

구글에서 sqlite jdbc driver 검색. 제일 위 사이트 클릭. downloads 탭 선택. sqlite-jdbc4-3.8.2-SNAPSHOT.jar 다운.

받은 jar파일을 C:\SqliteRoom 에 넣어줌. 그리고 add/edit 들어가서 sqlite-edit 눌러서 방금 jar파일을 add jars해서 추가해주고 리스트드라이버 잡아주고 

URL을 jdbc:sqlite:C:/sqliteroom/test.db로 바꿔줌. ok해서 Name을 Sqlite3해주고 User~~~체크, Auto Commit 체크 ~~ ok.

연결시켜주고 select * from helloworld; 하면 안되네.-> 오른쪽에 Tables에 helloworld 눌러서 다시 해주면 된다.


다시 sql editor 창에서 

CREATE TABLE telephone

(

  telnum CHAR(8) PRIMARY KEY,

  gubun INTEGER NOT NULL,

  irum VARCHAR(20) NOT NULL,

  howmany INTEGER NOT NULL,

  gibon INTEGER,

  fee INTEGER,

  tax INTEGER,

  total INTEGER

);

run 하고 오른쪽에 Tables를 refresh하면 telephone table이 들어온 것을 볼 수 있다.


이클립스의 전화요금 관리프로그램의 우측버튼 built path-configuration build path 들어가서libraries 탭에서 add External JARs에서 sqliteroom의 jar파일을 선택해준다.

main에서 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

//2. Driver Loading

try {

Class.forName("org.sqlite.JDBC");

System.out.println("Loading Success");

} catch (ClassNotFoundException e) {

System.out.println("Class Not Found");

}

//3. Connection

Connection conn = null;

String str = "jdbc:sqlite:C:/sqliteroom/test.db";

try{

conn = DriverManager.getConnection(str);

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

}

}

이렇게 해서 실행 시켜주어 connection 까지 완료한다.


dbinf.properties를 프로젝트에 넣어주고 내용을

DBDRIVER=org.sqlite.JDBC

DBURL=jdbc:sqlite:C:/SqliteRoom/test.db

로 바꿔줌.

다시 main을 

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

System.out.println("<<전화요금관리프로그램>>");

Scanner scan = new Scanner(System.in);

Main main = new Main();

int choice = 0;

while(true){

choice = main.showMenu(scan);

if(choice == 4) break;

switch(choice){

case 1 : Input input = new Input(scan);  input.input(); break; 

case 2 : Output output = new Output(); break;

case 3 : Search search = new Search(scan); search.search(); break;

}

}

System.out.println("Program is over...");

}

int showMenu(Scanner scan){

System.out.println("1:입력, 2:출력, 3:검색, 4:종료");

System.out.print(">> ");

return scan.nextInt();

}

}

이렇게 바꿔주고, 

DBConnection도

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

try{

conn = java.sql.DriverManager.getConnection(url);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}

이렇게 바꿔줌(바꿔준건 dbinf.properties의 경로밖에없음. 그냥 자바프로젝트에 넣어주어서)

실행하면 잘됨. 몇명 입력하고 Sqlite Database Browser로 확인하면 입력된 것을 볼 수 있다.


전화요금관리프로그램에서 delete만 추가된 버전을 만들면(수정한 것만 적음)

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

/* //2. Driver Loading

try {

Class.forName("org.sqlite.JDBC");

System.out.println("Loading Success");

} catch (ClassNotFoundException e) {

System.out.println("Class Not Found");

}

//3. Connection

Connection conn = null;

String str = "jdbc:sqlite:C:/sqliteroom/test.db";

try{

conn = DriverManager.getConnection(str);

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

//4. Statement 객체 생성

Statement stmt = null;

try{

stmt = conn.createStatement();

//5. Query 실행

StringBuffer sb = new StringBuffer();

sb.append("CREATE TABLE telephone(");

sb.append("telnum    CHAR(8)  PRIMARY KEY, ");

sb.append("gubun   INTEGER   NOT NULL,");

sb.append("irum    VARCHAR(20)  NOT NULL,");

sb.append("howmany   INTEGER   NOT NULL,");

sb.append("gibon   INTEGER,");

sb.append("fee   INTEGER, ");

sb.append("tax   INTEGER, ");

sb.append("total  INTEGER)");

stmt.executeUpdate(sb.toString());

System.out.println("Table Creation Success");

}catch(SQLException ex){

ex.printStackTrace();

}

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}*/

System.out.println("<<전화요금관리프로그램>>");

Scanner scan = new Scanner(System.in);

Main main = new Main();

int choice = 0;

while(true){

choice = main.showMenu(scan);

if(choice == 6) break;

switch(choice){

case 1 : Input input = new Input(scan);  input.input(); break; 

case 2 : Output output = new Output(); break;

case 3 : Search search = new Search(scan); search.search(); break;

case 4 : Delete delete = new Delete(scan); delete.delete(); break; 

//case 5 :

}

}

System.out.println("Program is over...");

}

int showMenu(Scanner scan){

System.out.println("1:입력, 2:출력, 3:검색, 4:삭제, 5:수정, 6:종료");

System.out.print(">> ");

return scan.nextInt();

}

}





import java.util.Scanner;

import java.util.Vector;



public class Delete {


private Scanner scan;

Delete(Scanner scan){

this.scan = scan;

}

void delete(){

System.out.print("1.이름으로 삭제,  2. 전화번호로 삭제 : ");

int choice = this.scan.nextInt();

this.scan.nextLine();

String sql = null;

if(choice == 1){  //이름으로 삭제

System.out.print("이름 : ");

String name = scan.nextLine();

sql = "DELETE FROM telephone WHERE irum = '" + name + "'";

}else if(choice == 2){   //전화번호로 삭제

System.out.print("전화번호 : ");

String telnum = scan.nextLine();

sql = "DELETE FROM telephone WHERE telnum = '" + telnum + "'";

}

CustomerController.delete(sql);

}

}






import java.sql.Connection;

import java.util.Vector;



public class CustomerController {

public static void delete(String sql){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

CustomerDAO.delete(conn, sql);

DBClose.close(conn);

}

public static Vector<CustomerVO> search(String sql){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

Vector<CustomerVO> vector = CustomerDAO.search(conn, sql);

DBClose.close(conn);

return vector;

}

public static void insert(CustomerVO c){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

CustomerDAO.insert(conn, c);

DBClose.close(conn);

}

public static Vector<CustomerVO> select(){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

Vector<CustomerVO> vector = CustomerDAO.select(conn);

DBClose.close(conn);

return vector;

}

}








import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Vector;


public class CustomerDAO {

public static void delete(Connection conn, String sql){

Statement stmt = null;

try {

stmt = conn.createStatement();

stmt.executeUpdate(sql);

System.out.println("Delete Success");

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

public static Vector<CustomerVO> search(Connection conn, String sql){

Vector<CustomerVO> vector = null;

Statement stmt = null;

ResultSet rs = null;

try{

stmt = conn.createStatement();

rs = stmt.executeQuery(sql);

if(rs.next()){ //있다면

vector = new Vector<CustomerVO>(1,1); //동명이인이 있을 수도있어 (1) 대신 (1,1)

do{

CustomerVO c = new CustomerVO();

c.setGubun(rs.getInt("gubun"));

c.setTelnum(rs.getString("telnum"));

c.setIrum(rs.getString("irum"));

c.setGibon(rs.getInt("gibon"));

c.setFee(rs.getInt("fee"));

c.setTax(rs.getInt("tax"));

c.setTotal(rs.getInt("total"));

vector.addElement(c);

}while(rs.next());

}

rs.close();

stmt.close();

}catch(SQLException ex){

ex.printStackTrace();

}

return vector;

}

public static Vector<CustomerVO> select(Connection conn){

Statement stmt = null;

ResultSet rs = null;

Vector<CustomerVO> vector = new Vector<CustomerVO>(1,1);

try {

stmt = conn.createStatement();

String sql = "SELECT * FROM Telephone";

rs = stmt.executeQuery(sql);

while(rs.next()){

CustomerVO c = new CustomerVO();

c.setGubun(rs.getInt("gubun"));

c.setTelnum(rs.getString("telnum"));

c.setIrum(rs.getString("irum"));

c.setGibon(rs.getInt("gibon"));

c.setFee(rs.getInt("fee"));

c.setTax(rs.getInt("tax"));

c.setTotal(rs.getInt("total"));

vector.addElement(c);

}

rs.close();

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

return vector;

}

public static void insert(Connection conn, CustomerVO c){

Statement stmt = null;

try {

stmt = conn.createStatement();

StringBuffer sb = new StringBuffer("INSERT INTO Telephone ");

sb.append("VALUES('" + c.getTelnum() + "'," + c.getGubun());

sb.append(",'" + c.getIrum() + "'," + c.getHowmany());

sb.append("," + c.getGibon() + "," + c.getFee() + "," + c.getTax());

sb.append("," + c.getTotal() + ")");

//System.out.println(sb.toString());

stmt.executeUpdate(sb.toString());

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

리눅스에서 sqlite3설치.

버츄얼 우분투를 켜서 sudo apt-get update 캐시업데이트.

sudo apt-get install sqlite3 libsqlite3-dev 해서 설치.

mkdir SqliteRoom으로 폴더하나 만들어주고 SqliteRoom 폴더안으로 들어가서  sqlite3 test.db 를 하면 테이블을 입력하면 test.db가 만들어질 것이다.

SQLite 끝.


=========================================================================

Server

1. Machine 이 서버.

2. OS 가 서버.

3. Program 이 서버

4. Server Service Start

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

MYSQL 시작.

윈도우즈에서  http://www.mysql.com/ 접속.

Download 탭에서 MySQL Community Edition의 다운로드로 이동.

MySQL Community Server (GPL) 선택.

밑에 쪽의 Windows(x86,64-bit), MySQL INstaller MSI 다운로드 선택.

Windows (x86, 32-bit), MSI Installer 5.6.17 234.7M 다운로드. 누르면 로그인 사인업 등이 잇는데 밑에 no thanks 클릭하면 다운로드됨.

다시  MySQL Community Edition의 다운로드로 이동 해서 

MySQL Workbench (GPL) 다운로드 선택 후 Windows (x86, 32-bit), MSI Installer 6.1.4 30.0M 다운로드 클릭. no thanks까지

다시 전으로 가서 MySQL Connectors 선택하고 Connector/J 선택. Windows (x86, 32-bit), MSI Installer 5.1.30 6.1M 다운로드. no thanks까지

http://www.sqlgate.com/ 접속. Download 탭이동. 

SQLGate for MySQL Developer 3.3.1.0 04/01/2014 11.7 M   다운로드.

그리고 다운받은 mysql-installer-community-5.6.17.0.msi 를 설치.

Install누르고 next, skip후 next 선택. Developer Default 선택. 나머지는 안건드리고 next.  그리고 기본설정대로 하고 execute.

동의하고 계속 install. 다 되면 next. 그리고 execute(보면 connector/j와 mysql Workbench 가 들어있는 것을 볼 수 있다. 괜히 깔았넹)

next, next, port number가 3306번인데 아래 파이어월을 열어준다에 체크가되어있다. 마지막에 show advanced option 체크 next.

MySQL Root Password 는 javamysql 을 해줌. next.

Windows Service Name은 두고 Start the MySQL Server at System Startup 체크 해제. next. 바로 next. next. next.

star MySQL Workbench after Setup 체크해제. finish.

실행시키는 첫번째 방법은 관리자권한으로 도스창열어줌. net start mysql56 시작. net stop mysql56 스탑.

두번째는 제어판에가서 관리도구가서 services 에서 MySQL56을 start or stop. 더블클릭해서 들어가면 Startup type에 Manual로 바꿔줌(부팅할때 자동으로 안올라오게 하기위해)

환경변수설정창에서 Path를 보면 MySQL이 올라온것을 볼 수 있다. 

그리고 환경변수 설정창에서 Systme variables에서 new를 선택.

name = MYSQL_HOME, values = C:\Program Files\MySQL\MySQL Server 5.6 로 설정.

그리고 Path에서 마지막에 %MYSQL_HOME%\bin 를 추가해줌.

일반 커맨드창을 열어서 set path해서 설정해줌.

그리고 mysql -h localhost -u root -p 하고 비번 javamysql 치면 mysql로 접속됨.


show databases; 를치면 기본적으로 설치된 데이터베이스를 볼 수 있다.

use world 를 치면 데이터베이스가 바뀐다.

show tables;

desc city;

use test

show tables;

DESC mysql.user;

select host, user, password from mysql.user;  //아무리 관리자라도 패스워드는 볼 수 없음.

exit   //종료


MySQL Workbench 실행.

local instance를 누르고 비번 javamysql을 누르면 들어가짐.


다시 관리자 명령프롬프트 접속. mysql -u root -p 엔터 비번쓰고

use mysql 엔터

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'javamysql';    @뒤는 클라이언트 머신을 얘기하는거임.

flush privileges; 엔터

위와 같이 설정하면  MySQL Workbench에서 Database 탭에서 connect to database 해서 다른 컴퓨터에 접근가능.(안되면 처음 홈화면에서 +해서 접속하면 됨)

명령프롬프트에서 접속할 때는 mysql -h 아이피or컴퓨터이름 -u root -p 로 다른컴퓨터로 접속가능.


아까 받은 SQLGateforMySQLDev.exe  설치.

호스트 localhost, 사용자 root, 암호 javamysql, 암호저장체크, 데이터베이스 mysql(접근할데이터베이스), 문자집합 utf8, 날짜형식 default. 접속테스트 누르고 접속.



이클립스 접속 해서 sql explorer 에서 new profile 들어가서 add/edit driver에서 mysql drivers 을 edit해서

extra class path 에서 add  JARs를 C:\Program Files\MySQL\Connector J 5.1.29의 mysql-conn~~~~.jar파일 선택.

list driver눌러서 driver class name을 com.mysql.jdbc.Driver 선택.

Example URL은 jdbc:mysql://localhost:3306/test로 해줌.(자기것에 3306포트에 아무것도 없는 test를 지정) . ok. ok

Name은 MySQL 5.6 , Driver는 MySQL Driver

autoLogon선택해서 user는 root, password는 javamysql 하고 autocommit 하고 ok.

커넥트하고 

select * FROM world.City

where countrycode = 'KOR';

이렇게 해보던지, 아니면 우측 위에 test를 world로 바꿔서 검색을 하던지.

하면 결과값볼수 있고.


다시 전화요금관리프로그램으로 이동.

build Path-configuration buildPath에 들어가서 libraries 탭에서 external jars에서 C:\Program Files\MySQL\Connector J 5.1.29 에서  mysql-conn~~~~.jar파일 선택.

Main에서

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;


public class Main {

public static void main(String[] args) {

//2. Driver Loading

try {

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

System.out.println("Loading Success");

} catch (ClassNotFoundException e) {

System.out.println("Class Not Found");

}

//3. Connection

Connection conn = null;

String str = "jdbc:mysql://Win8-22:3306/test";  //내컴터이름과 포트번호

try{

conn = DriverManager.getConnection(str,"root","javamysql"); //아이디,비번 넣야함.

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

//4. Statement 객체 생성

Statement stmt = null;

try{

stmt = conn.createStatement();

//5. Query 실행

StringBuffer sb = new StringBuffer();

sb.append("CREATE TABLE telephone(");

sb.append("telnum    CHAR(8)  PRIMARY KEY, ");

sb.append("gubun   INTEGER   NOT NULL,");

sb.append("irum    VARCHAR(20)  NOT NULL,");

sb.append("howmany   INTEGER   NOT NULL,");

sb.append("gibon   INTEGER,");

sb.append("fee   INTEGER, ");

sb.append("tax   INTEGER, ");

sb.append("total  INTEGER)");

stmt.executeUpdate(sb.toString());

System.out.println("Table Creation Success");

}catch(SQLException ex){

ex.printStackTrace();

}

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

}

위와같이해서 로딩, 연결, 테이블까지 만들어줌.

그리고 dbinfo.properties 를

DBDRIVER=com.mysql.jdbc.Driver

DBURL=jdbc:mysql://localhost:3306/test

DBUSER=root

DBPWD=javamysql

이와 같이 변경해줌.


그리고 DBConnection은 user와 pwd를 다시 추가했으니 다시변경.

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

String user = info.getProperty("DBUSER");

String pwd = info.getProperty("DBPWD");

try{

conn = java.sql.DriverManager.getConnection(url, user, pwd);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}

그리고 다시 실행해보면 실행이 잘된다.


----------------------------------------------------

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

우분투 폴더 복사.
복사한 우분투 켜서 sudo apt-get update
sudo apt-get install mysql-server mysql-client 엔터.
root password 쓰는 것이 뜨면 javamysql 써주고. 설치 끝.
확인하면 sudo netstat -tap | grep mysql 을 써서 확인.
sudo service mysql restart 엔터.
sudo gedit으로 열어서 /etc/mysql 에서 my.cnf를 열음.
[client]
port = 3306
이 부분 바로 아래에
default-charset=utf8  를 추가.
그리고 48라인
bind-address = 127.0.0.1 을 주석처리 앞에 #해서 #bind-address = 127.0.0.1 해줌. //이렇게 해야 다른머신에서 들어올 수 있음.
이게 안되네 default-charset=utf8  주석처리 해줌. #default_charset=utf8
그리고 mysql 치면 mysql로 들어올 수 있음. quit 해서 나와주고
mysql -u root -p 로 관리자 권한 로그인. 비번은 javamysql.
select host,user, password from mysql.user; 으로 보면. 계정없이 들어가는 것을 볼 수 있다. 이것은 보안에 상당한 위험을 줌.
delete from mysql.user where user = ''; 로 user 가 공백인 것을 삭제. 확인하면  지워진 것을 볼 수 있음. quit로 나오고.
mysql -u root -p 으로 접속후 flush privileges; 을 해서 프리빌리지해줌. quit 해서 다시 mysql쓰면 접속안됨. 이제 게스트계정으로는 접속 불가.
다시 mysql -u root -p으로 접속 비번쓰고.  GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'javamysql';  해서 루트계정은 모든 권한을 줌
flush privileges; 해서 디비를 반영시키고 
exit 로 나와서  sudo service mysql restart 재시작.
그리고 다시 sudo gedit으로 my.cnf를 열어서 default-character-set=utf8 로 바꿔주고 sudo service mysql restart 해줌.

위에서 했던 것처럼. 우분투에서는 방화벽 3306을 풀고 MySQLWorkbench로 우분투에 접속해보고, 우분투에서는  mysql -h 접속할아이피 -u root -p 로 접속. 해본다.

sudo apt-get remove mysql-server mysql-client 로 삭제.(근데 서비스는 됨...)
첫번째 우분투 카피본 삭제.
-----------
두번째 우분투 카피본을 켜봄.
http://www.mysql.com/ 로 접속. Download 탭에가서
MySQL Community Edition (GPL) 의 다운로드 선택.
MySQL Community Server (GPL) 선택.
MySQL Community Server 5.6.17 에서 Select Platform: 을 Debian Linux로 선택하고.
Debian Linux 6.0 (x86, 32-bit), DEB 5.6.17 276.3M 다운로드 선택. no thanks.
그리고 구글에가서 libaio_0.3.104-1_i386.deb download 검색. libaio_0.3.104-1_i386.deb [6018 bytes] - Download Mirrors  사이트로 들어감.
2013-07-18  ftp://ftp.vss.spb.ru/pub/unix/oracle/libaio_0.3.104-1_i386.deb 선택해서 다운로드.
터미널켜서 먼저 sudo apt-get update 로 캐시업데이트.
cd Downloads로 이동. sudo apt-get install build-essential 하면 이미 깔려있넹.
sudo dpkg -i lib*.deb 로  libaio_0.3.104-1_i386.deb 설치.
sudo groupadd mysql
sudo useradd -r -g mysql mysql   //mysql계정을 만들면서 mysql 그룹을 만듬.
sudo dpkg -i mysql*.deb 로 mysql-5.6.17-debian6.0-i686.deb 을 설치.
ls /opt/ 명령어로 mysql 확인 가능.
소유권 변경:  sudo chown -R mysql:mysql /opt/mysql      //앞의 mysql계정:mysql그룹
ls -l /opt/mysql 으로 확인.
cd /opt/mysql/server-5.6 로 이동.  ls -l 쳐보면 계정과 그룹이 mysql로 바뀌어있음을 볼 수 있다.
sudo passwd mysql 을 쳐서 패스워드를 주자. mysql로 비번을 줌.
su mysql 하고 비번쓰는곳에도 mysql 그러면 시작됨.
pwd //위치확인
ls  //현재 폴더의 파일 확인
cd support -files 에 mysql-server 확인.
cd.. 해서 cd scripts 로 감.
./mysql_install_db --user=mysql    //이노디비설치
cd .. -> cd bin 이동. 
./mysqld_safe --user=mysql &  // &은 백그라운드파일~~ 
ps -ef | grep mysql    //현재프로세스에 올라와있는 목록 중에 mysql 들어가 있는 것만 필터
exit  로 나와주고.
cd support-files 로  들어가서. sudo cp ./mysql.server /etc/init.d/mysqld   로 카피.
데몬서비스를 올렸으니 sudo update-rc.d mysqld defaults   업데이트하고, //앞으로 mysqld 임.
cd 로 내 집에가서 sudo service mysqld start  스타트
sudo service mysqld restart    리스타트.
ps -ef | grep mysqld 로 서비스가 잘돌아가는 지 확인.
sudo service mysqld stop  스탑
sudo service mysqld restart  리스타트
sudo service mysqld start  스타트
sudo service mysqld status  상태확인 . 이렇게 네가지.
sudo gedit /etc/profile 로 들어가서 .
#--------------------------------------------------
# Java Settings
#--------------------------------------------------

JAVA_HOME=/usr/lib/jvm/jdk1.7.0_51
MYSQL_HOME=/opt/mysql/server-5.6
CLASSPATH=.:/usr/lib/jvm/jdk1.7.0_51/lib/tools.jar
PATH=$JAVA_HOME/bin/:$PATH:$MYSQL_HOME/bin

export JAVA_HOME
export MYSQL_HOME
export CLASSPATH
export PATH
위에서 추가한 건 MYSQL관련부분.
확인 해보면  source /etc/profile
echo $MYSQL_HOME
echo $PATH
which mysql
그리고 mysql치면 로그인되는데 게스트가 로그인이 안되게 해보자.
일단 터미널에서 mysqladmin -u root password javamysql 해서 비번을 정해주고.
mysql -u root -p 로 접속. 비번써주고.
select host,user, password from mysql.user; 으로 user가 공백인 것 확인.
delete from mysql.user WHERE user='';  로 user가 공백인 것 삭제.
select host,user, password from mysql.user; 로 보면 삭제 된 것을 볼 수 있다.
UPDATE mysql.user SET password=password('javamysql') WHERE user='root'; 로 user가 root인 계정의 비번을 javamysql로 바꿔줌. password의 함수로 인코딩해서 보이지않게 해줌.
flush privileges;   권한 적용. quit로 나가서   mysql -h 127.0.0.1 -u root -p 을 쳐서 로컬호스트로 접속을 하게 하면 비번을 적어야하는 것을 볼 수 있다.
또 접속해서 GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'javamysql';  해서 루트계정은 모든 권한을 줌
flush privileges; 로 마무리.
-----------------------
다시 전화요금관리프로그램가서 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
public static void main(String[] args) {
//2. Driver Loading
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Loading Success");
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found");
}
//3. Connection
Connection conn = null;
String str = "jdbc:mysql://192.168.56.130:3306/test";  //리눅스 컴터 아이피.
try{
conn = DriverManager.getConnection(str,"root","javamysql"); //아이디,비번 넣야함.
System.out.println("Connection Success");
}catch(SQLException ex){
System.out.println("Connection failure");
}
//4. Statement 객체 생성
Statement stmt = null;
try{
stmt = conn.createStatement();
//5. Query 실행
StringBuffer sb = new StringBuffer();
sb.append("CREATE TABLE telephone(");
sb.append("telnum    CHAR(8)  PRIMARY KEY, ");
sb.append("gubun   INTEGER   NOT NULL,");
sb.append("irum    VARCHAR(20)  NOT NULL,");
sb.append("howmany   INTEGER   NOT NULL,");
sb.append("gibon   INTEGER,");
sb.append("fee   INTEGER, ");
sb.append("tax   INTEGER, ");
sb.append("total  INTEGER)");
stmt.executeUpdate(sb.toString());
System.out.println("Table Creation Success");
}catch(SQLException ex){
ex.printStackTrace();
}
try{
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
로 실행 시켜주고.
dbinfo.properties을 아래와 같이 바꿔줌.
DBDRIVER=com.mysql.jdbc.Driver
DBURL=jdbc:mysql://192.168.56.130:3306/test
DBUSER=root
DBPWD=javamysql

CustomerDAO.java 에서 Telephone을 telephone으로 바꿔준다.
실행해보면 출력에서 한글이 화면이 깨진다.
sudo gedit 해서 열어서 /opt/mysql/server-5.6에서 my.cnf 열음.
4라인 [mysqld] 위에 
[client]
default-character-set=utf8  을 넣어준다.
설정이 바뀌었으니  sudo service mysqld restart 로 재시작해줌.  다시 실행해도 한글 안됨.
다시 my.cnf에 들어가서 default-character-set=utf8 를 주석처리 #default-character-set=utf8  해줌.
다른방법:
import java.io.UnsupportedEncodingException;

public class Utility {
public static String kotoen(String ko){
String en = null;
try{
en = new String(ko.getBytes("KSC5601"), "ISO8859_1");
}catch(UnsupportedEncodingException ex){}
return en;
}
public static String entoko(String en){
String ko = null;
try{
ko = new String(en.getBytes("ISO8859_1"), "KSC5601");
}catch(UnsupportedEncodingException ex){}
return ko;
}
}
를 추가해주고. 
CustomerDAO를 아래와 같이 바꿔줌.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;


public class CustomerDAO {
public static void delete(Connection conn, String sql){
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
System.out.println("Delete Success");
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Vector<CustomerVO> search(Connection conn, String sql){
Vector<CustomerVO> vector = null;
Statement stmt = null;
ResultSet rs = null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if(rs.next()){  //있다면
vector = new Vector<CustomerVO>(1,1);
do{
CustomerVO c = new CustomerVO();
c.setGubun(rs.getInt("gubun"));
c.setTelnum(rs.getString("telnum"));
c.setIrum(Utility.entoko(rs.getString("irum")));
c.setGibon(rs.getInt("gibon"));
c.setFee(rs.getInt("fee"));
c.setTax(rs.getInt("tax"));
c.setTotal(rs.getInt("total"));
vector.addElement(c);
}while(rs.next());
}
rs.close();
stmt.close();
}catch(SQLException ex){
ex.printStackTrace();
}
return vector;
}
public static Vector<CustomerVO> select(Connection conn){
Statement stmt = null;
ResultSet rs = null;
Vector<CustomerVO> vector = new Vector<CustomerVO>(1,1);
try {
stmt = conn.createStatement();
String sql = "SELECT * FROM telephone";
rs = stmt.executeQuery(sql);
while(rs.next()){
CustomerVO c = new CustomerVO();
c.setGubun(rs.getInt("gubun"));
c.setTelnum(rs.getString("telnum"));
c.setIrum(Utility.entoko(rs.getString("irum")));
c.setGibon(rs.getInt("gibon"));
c.setFee(rs.getInt("fee"));
c.setTax(rs.getInt("tax"));
c.setTotal(rs.getInt("total"));
vector.addElement(c);
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return vector;
}
public static void insert(Connection conn, CustomerVO c){
Statement stmt = null;
try {
stmt = conn.createStatement();
StringBuffer sb = new StringBuffer("INSERT INTO telephone ");
sb.append("VALUES('" + c.getTelnum() + "'," + c.getGubun());
sb.append(",'" + Utility.kotoen(c.getIrum()) + "'," + c.getHowmany());
sb.append("," + c.getGibon() + "," + c.getFee() + "," + c.getTax());
sb.append("," + c.getTotal() + ")");
//System.out.println(sb.toString());
stmt.executeUpdate(sb.toString());
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
이렇게 하면한글이 출력시 화면이 깨지지 않음.
================================================================================================
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
CentOS 설치. 
typical-> ISO image 를 centos iso파일 선택. 비밀번호 아무거나 주고 next
경로 지정해주고   50GB/single file선택.
customize hardware 눌러서 메모리 2GB 코어4개 선택. automaticaly 체크 해제하고 
edit 눌러 CD/DVD2 삭제해주고  CD/DVD 경로를  centos ISO 파일 지정해주고.
설치 페이지에서 맨위 Install or upgrade 선택. 
skip 선택.
next-> English next -> next -> Basic ~~ next -> yes discard any data -> name 은 CentOS-22 next ->Seoul next
->password 는 자기꺼쓰고 next -> create custom Layout 선택.
Free눌러서 create ->standard create
systme type : swap, size: 2048 , fixed size 선택
다시 free 눌러서 create ->standard create 
Mount point : /boot , size 512, fixed size 선택
다시 free 눌러서 create ->standard create
Mount point : / , File to maximum allowable size  선택
next -> format -> write change to disk , next
-> next -> Desktop 선택 next -> 다 돼면 reboot ->foward x2
-> username ~~ 다 써주고 -> yes
->syncornize~~~ 체크해서 하나 선택후 next -> Enable Kdump 체크해제 fisnih yes
다 설치되면 centos 는 기본적으로 네트웍이 안되어 네트워크를 눌러서 eth0을 눌러 잡아줘야함.
system-preference-Input method  Enable 체크해서 Input method prefrence 눌러서 
Input method 탭에서 코리안 추가 로그아웃후 로그인하면 ctrl+space로 한글변환가능




 









http://db.apache.org/ 들어가서 subprojects-Dearby-Download 탭선택. 

10.10.1.1 (April 15, 2013 / SVN 1458268) 눌러서

other mirror.apache-kr.org 선택해서 db-derby-10.10.1.1-bin.zip  다운.

압축을 풀고 Apache Derby 로 폴더이름 변경. C:\Program Files에 폴더 붙여넣어줌.

환경변수를 설정하기 위해 환경변수설정창 가서 System variables-New를 넣어서 name에는 DERBY_HOME , value: C:\Program Files\Apache Derby  넣어줌.

그리고 Path에서 Edit 들어가서 마지막에 %DERBY_HOME%\bin; 을 넣어줌.

명령프롬프트 창에가서 set derby_home  해서 설정해줌. set path 로 설정 셋.

cd\ 해서 md derbyroom 을 쳐서 폴더를 하나 만들어줌.  cd derbyroom으로 폴더안으로 들어가서

ij치면 자바 더비를 사용할 수 있음.

거기서 connect 'jdbc:derby:mydb;create=true'; 를 쳐서 디비를 만들어줌.

그리고 CREATE TABLE helloworld 엔터

(

id integer primary key,

pwd varchar(20) NOT NULL

);

해서 테스트를 해보면.

INSERT INTO helloworld VALUES(1, '123456');

INSERT INTO helloworld VALUES(2, '1111');

INSERT INTO helloworld VALUES(3, 'P@$$WOrd'); 

를 입력해주고

SELECT * FROM helloworld; 를 쳐서 입력한 것을 확인.

exit;으로 종료.

이클립스에 들어가서 sql explorer 을 띄어 

new profile에서 driver 에서 add/exit 를  눌러서 Apache Derby-Network Server 선택해서 edit 눌러서

extra Class path 에서 add JARs에서 

C:\Program Files\Apache Derby\lib 에서 derby.jar 선택.

그리고 list Drivers를 눌러주고 Driver class Name을 제일밑에 org.~~~~.EmbeddedDriver 선택.

그리고 Example URL을 jdbc:derby:C:/derbyroom/mydb;create=true; 으로 고쳐줌.(내가 나에게 접속하고 이름은 mydb 로 주었기 때문에). 그리고 ok. ok.

Driver는 지금 설정한 Apache Derby ~~ 선택하고 name은 Derby 하고 user name is not ~~~~~~ 체크

AutoCommit 체크 해서 ok. 

그리고 SELECT * FROM helloworld; 를 선택하면 아까 작성한 것을 볼 수 있다.



지난시간에 TelephoneMgmt를 Derby를 사용하여 해보자.

프로젝트 우측버튼 build path- configuration build path 눌러서 libraries 탭에서 Add External JARs를 눌러 C:\Program Files\Apache Derby\lib에서 derby.jar을 눌러줌.

그래야 Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); 을 쓸수 있음.

dbinfo.properties을 아래처럼 변경.

DBDRIVER=org.apache.derby.jdbc.EmbeddedDriver

DBURL=jdbc:derby:c:/derbyroom/telephone;create=true


main을 아래와 같이 실행시켜주고 테이블을 디비에 만들어줌. 그리고 주석처리를 바꿔줌. 기존 주석처리 안된 것은 주석처리를, 주석처리 되어있는건 풀고.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

//2. Driver Loading

try {

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

System.out.println("Loading Success");

} catch (ClassNotFoundException e) {

System.out.println("Class Not Found");

}

//3. Connection

Connection conn = null;

String str = "jdbc:derby:C:/derbyroom/telephone;create=true";

try{

conn = DriverManager.getConnection(str);

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

//4. Statement 객체 생성

Statement stmt = null;

try{

stmt = conn.createStatement();

//5. Query 실행

StringBuffer sb = new StringBuffer();

sb.append("CREATE TABLE telephone(");

sb.append("telnum    CHAR(8)  PRIMARY KEY, ");

sb.append("gubun   INTEGER   NOT NULL,");

sb.append("irum    VARCHAR(20)  NOT NULL,");

sb.append("howmany   INTEGER   NOT NULL,");

sb.append("gibon   INTEGER,");

sb.append("fee   INTEGER, ");

sb.append("tax   INTEGER, ");

sb.append("total  INTEGER)");

stmt.executeUpdate(sb.toString());

System.out.println("Table Creation Success");

}catch(SQLException ex){

ex.printStackTrace();

}

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

/*System.out.println("<<전화요금관리프로그램>>");

Scanner scan = new Scanner(System.in);

Main main = new Main();

int choice = 0;

while(true){

choice = main.showMenu(scan);

if(choice == 4) break;

switch(choice){

case 1 : Input input = new Input(scan);  input.input(); break; 

case 2 : Output output = new Output(); break;

//case 3 :

}

}

System.out.println("Program is over...");*/

}

int showMenu(Scanner scan){

System.out.println("1:입력, 2:출력, 3:검색, 4:종료");

System.out.print(">> ");

return scan.nextInt();

}

}



DBConnection.java는 아래와 같이 바꿔줌.


import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("D:\\Downloads\\dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

try{

conn = java.sql.DriverManager.getConnection(url);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}

바뀐건 userid, userpwd부분을 삭제한 것.

그리고 실행. 잘됨.


잘되는 것을 확인했으니 지난번에 못한 검색을 추가하는 버전을 만들면.

전화요금관리프로그램 

public class CustomerVO {

private int gubun;

private String telnum;

private String irum;

private int howmany;

private int gibon;

private int fee;

private int tax;

private int total;

public CustomerVO(){}

public CustomerVO(int gubun, String telnum, String irum, int howmany) {

this.gubun = gubun;

this.telnum = telnum;

this.irum = irum;

this.howmany = howmany;

}

@Override

public String toString(){

return String.format("%d\t%s\t%s\t%,d\t%,d\t%,d\t%,d",

                   this.gubun, this.telnum, this.irum, this.gibon,

                   this.fee, this.tax, this.total);

}

public int getGubun() {

return gubun;

}

public void setGubun(int gubun) {

this.gubun = gubun;

}

public String getTelnum() {

return telnum;

}

public void setTelnum(String telnum) {

this.telnum = telnum;

}

public String getIrum() {

return irum;

}

public void setIrum(String irum) {

this.irum = irum;

}

public int getHowmany() {

return howmany;

}

public void setHowmany(int howmany) {

this.howmany = howmany;

}

public int getGibon() {

return gibon;

}

public void setGibon(int gibon) {

this.gibon = gibon;

}

public int getFee() {

return fee;

}

public void setFee(int fee) {

this.fee = fee;

}

public int getTax() {

return tax;

}

public void setTax(int tax) {

this.tax = tax;

}

public int getTotal() {

return total;

}

public void setTotal(int total) {

this.total = total;

}

}





import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

/* //2. Driver Loading

try {

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

System.out.println("Loading Success");

} catch (ClassNotFoundException e) {

System.out.println("Class Not Found");

}

//3. Connection

Connection conn = null;

String str = "jdbc:derby:C:/derbyroom/telephone;create=true";

try{

conn = DriverManager.getConnection(str);

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

//4. Statement 객체 생성

Statement stmt = null;

try{

stmt = conn.createStatement();

//5. Query 실행

StringBuffer sb = new StringBuffer();

sb.append("CREATE TABLE telephone(");

sb.append("telnum    CHAR(8)  PRIMARY KEY, ");

sb.append("gubun   INTEGER   NOT NULL,");

sb.append("irum    VARCHAR(20)  NOT NULL,");

sb.append("howmany   INTEGER   NOT NULL,");

sb.append("gibon   INTEGER,");

sb.append("fee   INTEGER, ");

sb.append("tax   INTEGER, ");

sb.append("total  INTEGER)");

stmt.executeUpdate(sb.toString());

System.out.println("Table Creation Success");

}catch(SQLException ex){

ex.printStackTrace();

}

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}*/

System.out.println("<<전화요금관리프로그램>>");

Scanner scan = new Scanner(System.in);

Main main = new Main();

int choice = 0;

while(true){

choice = main.showMenu(scan);

if(choice == 4) break;

switch(choice){

case 1 : Input input = new Input(scan);  input.input(); break; 

case 2 : Output output = new Output(); break;

case 3 : Search search = new Search(scan); search.search(); break;

}

}

System.out.println("Program is over...");

}

int showMenu(Scanner scan){

System.out.println("1:입력, 2:출력, 3:검색, 4:종료");

System.out.print(">> ");

return scan.nextInt();

}

}







import java.util.Scanner;


public class Input {

private Scanner scan;

Input(Scanner scan){

this.scan = scan;

}

void input(){

System.out.print("구분 : ");   int gubun = this.scan.nextInt();

System.out.print("전화번호 : "); String telnum = this.scan.next();

this.scan.nextLine();

System.out.print("성명 : "); String irum = this.scan.nextLine();

System.out.print("통화량 : ");  int howmany = this.scan.nextInt();

this.scan.nextLine();

CustomerVO c = new CustomerVO(gubun, telnum, irum, howmany);

Calc calc = new Calc(c);

CustomerController.insert(c);

}

}







import java.util.Scanner;

import java.util.Vector;



public class Search {

private Scanner scan;

Search(Scanner scan){

this.scan = scan;

}

void search(){

System.out.print("1.이름으로 검색,  2. 전화번호로 검색 : ");

int choice = this.scan.nextInt();

this.scan.nextLine();

String sql = null;

if(choice == 1){  //이름으로 검색

System.out.print("이름 : ");

String name = scan.nextLine();

sql = "SELECT * FROM telephone WHERE irum = '" + name + "' ";

}else if(choice == 2){   //전화번호로 검색

System.out.print("전화번호 : ");

String telnum = scan.nextLine();

sql = "SELECT * FROM telephone WHERE telnum = '" + telnum + "' ";

}

Vector<CustomerVO> vector = CustomerController.search(sql);

if(vector == null){

System.out.println("조건에 맞는 데이터가 없습니다.");

}

else{

for(int i = 0 ; i < vector.size() ; i++){

CustomerVO c = vector.get(i);

System.out.println(c);

}

}

}

}






public class Calc {

private CustomerVO c;

Calc(CustomerVO c){

this.c = c;

calc();

}

void calc(){

//1)입력되는 값이 구분이 1이면 영업용, 2이면 관청용, 3이면 가정용이다.

int gibon = (c.getGubun() == 1) ? 6000 :

                 (c.getGubun() == 2) ? 4800 : 3000;

//2)기본요금은 영업용이 6,000원, 관청용이 4,800원, 가정용이 3,000원이다.

//3)통화료는 1통화에 대하여 12원이다.

int fee = c.getHowmany() * 12;

//4)세금은 기본 요금과 통화료를 합한 금액의 10%를 부과한다.

int tax = (int)((gibon + fee) * 0.1);

int total = gibon + fee + tax;

c.setGibon(gibon);

c.setFee(fee);

c.setTax(tax);

c.setTotal(total);

}

}





import java.sql.Connection;

import java.util.Vector;


public class CustomerController {

public static Vector<CustomerVO> search(String sql){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

Vector<CustomerVO> vector = CustomerDAO.search(conn, sql);

DBClose.close(conn);

return vector;

}

public static void insert(CustomerVO c){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

CustomerDAO.insert(conn, c);

DBClose.close(conn);

}

public static Vector <CustomerVO> select(){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

Vector<CustomerVO> vector = CustomerDAO.select(conn);

DBClose.close(conn);

return vector;

}

}





import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Vector;


public class CustomerDAO {

public static Vector<CustomerVO> search(Connection conn, String sql){

Vector<CustomerVO> vector = null;

Statement stmt = null;

ResultSet rs = null;

try{

stmt = conn.createStatement();

rs = stmt.executeQuery(sql);

if(rs.next()){ //있다면

vector = new Vector<CustomerVO>(1,1); //동명이인이 있을 수도있어 (1) 대신 (1,1)

do{

CustomerVO c = new CustomerVO();

c.setGubun(rs.getInt("gubun"));

c.setTelnum(rs.getString("telnum"));

c.setIrum(rs.getString("irum"));

c.setGibon(rs.getInt("gibon"));

c.setFee(rs.getInt("fee"));

c.setTax(rs.getInt("tax"));

c.setTotal(rs.getInt("total"));

vector.addElement(c);

}while(rs.next());

}

rs.close();

stmt.close();

}catch(SQLException ex){

ex.printStackTrace();

}

return vector;

}

public static Vector<CustomerVO> select(Connection conn){

Statement stmt = null;

ResultSet rs = null;

Vector<CustomerVO> vector = new Vector<CustomerVO>(1,1);

try {

stmt = conn.createStatement();

String sql = "SELECT * FROM Telephone";

rs = stmt.executeQuery(sql);

while(rs.next()){

CustomerVO c = new CustomerVO();

c.setGubun(rs.getInt("gubun"));

c.setTelnum(rs.getString("telnum"));

c.setIrum(rs.getString("irum"));

c.setGibon(rs.getInt("gibon"));

c.setFee(rs.getInt("fee"));

c.setTax(rs.getInt("tax"));

c.setTotal(rs.getInt("total"));

vector.addElement(c);

}

rs.close();

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

return vector;

}

public static void insert(Connection conn, CustomerVO c){

Statement stmt = null;

try {

stmt = conn.createStatement();

StringBuffer sb = new StringBuffer("INSERT INTO Telephone ");

sb.append("VALUES('" + c.getTelnum() + "'," + c.getGubun());

sb.append(",'" + c.getIrum() + "'," + c.getHowmany());

sb.append("," + c.getGibon() + "," + c.getFee() + "," + c.getTax());

sb.append("," + c.getTotal() + ")");

//System.out.println(sb.toString());

stmt.executeUpdate(sb.toString());

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}







import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;



public class DBClose {

public static void close(Connection conn){

try{

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

public static void close(Connection conn, Statement stmt){

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

public static void close(Connection conn, Statement stmt, ResultSet rs){

try{

if(rs != null) rs.close();

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

}







import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("D:\\Downloads\\dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

try{

conn = java.sql.DriverManager.getConnection(url);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}






import java.util.Vector;


public class Output {

Output(){

Vector<CustomerVO> vector = CustomerController.select();

for(int i = 0 ; i < vector.size() ; i++){

CustomerVO c = vector.get(i);

System.out.println(c);

}

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ=====================================================================================================

리눅스에서 

리눅스에서도 http://db.apache.org/에 접속해서 derby-download에서 db-derby-10.10.1.1-src.tar.gz 다운.

압축을 푼후 폴더이름을 Derby 로 변경. 터미널 켜서 Derby 폴더가 있는 곳으로 가서 sudo mv Derby /usr/lib/jvm 로 폴더이동.

sudo gedit /etc/profile 로 들어가서.

예전에 자바세팅한 것을

#----------------------------------------------

# Java Settings

#----------------------------------------------


JAVA_HOME=/usr/lib/jvm/jdk1.7.0_51

DERBY_HOME=/usr/lib/jvm/Derby

CLASSPATH=.:/usr/lib/jvm/jdk1.7.0_51/lib/tools.jar

PATH=$JAVA_HOME/bin/:$PATH:$DERBY_HOME/bin


export JAVA_HOME

export DERBY_HOME

export CLASSPATH

export PATH


위와 같이 변경. 터미널에서 source /etc/profile 엔터.

echo $PATH으로 확인.

home으로 가서(/home/mino)  mkdir DerbyRoom 하나 만들어줌.

만들어준 폴더에 들어가서

ij

connect 'jdbc:derby:mydb;create=true';

CREATE TABLE helloworld

(

id integer primary key,

pwd varchar(20) not null);

INSERT INTO helloworld VALUES(1, '123456');

INSERT INTO helloworld VALUES(2, 'P@$$W0rd');

SELECT * FROM helloworld;


이클립스에 sql explorer 사용을 위해서.

구글에서 sql explorer 검색 해서 Eclipse SQL Explorer들어가서 download 들어가서 SQL Explorer Plugin 누르고  

3.6.1- sqlexplorer_plugin-3.6.1_SR6.zip 눌러서 다운. 압축풀고 이클립스폴더에 feature폴더 plugins 폴더에 각각 넣어줌.

이클립스를 다시켜서 sql explore를 열어서 new profile 에서 add/edit drivers 선택해서 apach derby 를 선택해 edit 해서  

add jars 해서  /usr/lib/jvm/Derby/lib/derby.jar 선택. list Drivers 누르고 

driver class name 을 org.~~~~.EmbeddedDriver 선택. example URL 을  jdbc:derby:/home/mino/DerbyRoom/mydb;create=true; 써줌.

ok누르고 Name은 Derby User name is~~~ 체크 auto commit 체크.


cd /usr/lib/jvm/Derby/lib 에 들어가서 chmod +x *.* 을 써서 실행 가능하게 함. 그리고 이 위치에서 java -jar derbyrun.jar server start  엔터를 하면  쭈르륵 뜬걸 볼 수 있다.(에러발생?)

gedit을 열어서 open 해서 /usr/lib/jvm/jdk_1.7.0_51/jre/lib/security/java.policy 를 열어줌. 

여기서 23번째 줄에서 localhost:1527로 바꿔줌.

그리고 위에 java -jar derbyrun.jar server start를 다시 써주면. started 된것을 볼 수 있다.

또 다른 확인 방법 하나- 터미널을 하나 더 켜서 netstat -ap | grep "LISTEN" 엔터.


기존것을 다 지우고 new profile 에서  add/edit 해서 extra class path에서 /usr/lib/jvm/Derby/lib/derbyclient.jar 해주고 

list Drivers 누르면 Driver Class Name 을 org.apache.derby.jdbc.ClientDriver를 선택.

URL은 jdbc:derby://localhost:1527/mydb;create=true; 해주고. Name은 NetworkDerby

아까 started 된 것은 계속 되고 있어야함. 


서버 종료는 cd /usr/lib/jvm/Derby/lib 이동해서

java -jar derbyrun.jar server shutdown  하면 서버를 종료할 수 있다.


우분투(클라이언트)에서 버츄얼우분투의 접속은

서버측에서 java -jar derbyrun.jar server start -h 자기아이피 해서 서버를 열고 

클라이언트에서 접속하면 성공. 그리고 서버측에서 /usr/lib/jvm/Derby/lib/mydb 가 있는 것을 볼 수있다.

(클라이언트 측에서는 jdbc:derby://서버아이피:1527/mydb;create=true; 

서버측에서는 위의 리눅스 시작부분부터 여기서 23번째 줄에서 localhost:1527로 바꿔줌.부분까지 설정. 하면됨)




ODBC 설정. Control Panel\All Control Panel Items\Administrative Tools\ODBC Data Sources 들어가서

System DSN 탭에서 Add눌러서 .mdb or .accdb 택하고 확인. data source name에 이름(난 school) 써주고(ODBC 이름), 데이터베이스 선택 을 눌러서 사용할 액세스파일(이미 만든 school)을 지정해줌.

advanced 누르면 아이디 비번을 정해줄 수 있다. 아디scott, 비번tiger  해줌.

그리고 이클립스에서 window- other perspective 에서 sql Explorer 선택.

new-connection profile에서 name은 아무거나, Driver는 jdbc odbc bridget 해주고 URL : jdbc:odbc:school(school은 아까정한 odbc이름). User는 scott, password는 tiger.

Auto Logon 과 Auto Commit 체크.


메모장을 열어 아래와 같이 적어서 저장해줌. dbinfo.properties 로 모든파일로 저장해서 d: downloads폴더에 저장.

DBDRIVER=sun.jdbc.odbc.JdbcOdbcDriver

DBURL=jdbc:odbc:school

DBUSER=scott

DBPWD=tiger


여기까진 설정.


3/27성적관리프로그램에서 디비추가(원본보기만활성화)

public class Student implements Comparable<Student> {

private String hakbun, name;

private int kor, eng, mat, edp, tot, ranking;

private double avg;

private char grade;

public Student(){}

public Student(String hakbun, String name, int kor, int eng, int mat, int edp) {

this.hakbun = hakbun;

this.name = name;

this.kor = kor;

this.eng = eng;

this.mat = mat;

this.edp = edp;

this.ranking = 1;

}

@Override

public int compareTo(Student s){

return this.getTot() - s.getTot();

}

public String [] toArray(){

String [] array = new String[10];

array[0] = this.hakbun;   array[1] = this.name;

array[2] = String.valueOf(this.kor);       array[3] = String.valueOf(this.eng);     

array[4] = String.valueOf(this.mat);       array[5] = String.valueOf(this.edp);     

array[6] = String.valueOf(this.tot);         array[7] = String.valueOf(this.avg);

array[8] = String.valueOf(this.grade);    array[9] = String.valueOf(this.ranking);          

return array;

}

@Override

public String toString(){

return String.format("%-10s%7s%5d%5d%5d%5d%5d%10.2f%5c%5d\n",

this.hakbun, this.name, this.kor, this.eng, this.mat, this.edp,

this.tot, this.avg, this.grade, this.ranking);

}

public String getHakbun() {

return hakbun;

}

public void setHakbun(String hakbun) {

this.hakbun = hakbun;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getKor() {

return kor;

}

public void setKor(int kor) {

this.kor = kor;

}

public int getEng() {

return eng;

}

public void setEng(int eng) {

this.eng = eng;

}

public int getMat() {

return mat;

}

public void setMat(int mat) {

this.mat = mat;

}

public int getEdp() {

return edp;

}

public void setEdp(int edp) {

this.edp = edp;

}

public int getTot() {

return tot;

}

public void setTot(int tot) {

this.tot = tot;

}

public int getRanking() {

return ranking;

}

public void setRanking(int ranking) {

this.ranking = ranking;

}

public double getAvg() {

return avg;

}

public void setAvg(double avg) {

this.avg = avg;

}

public char getGrade() {

return grade;

}

public void setGrade(char grade) {

this.grade = grade;

}

}







import java.awt.Container;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JTabbedPane;


public class Main {

private JFrame f;

private JTabbedPane tab;

private Container con;

private Main(){

this.f = new JFrame("성적관리프로그램 V3.0");

this.tab = new JTabbedPane();

this.con = this.f.getContentPane();

}

private void display(){

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.f.setResizable(false);

this.tab.addTab("일반데이터입력", new InputPanel(this.f, this.tab));

this.tab.addTab("데이터출력", new OutputPanel(this.f));

this.con.add(this.tab);

this.f.setSize(500, 400);

this.f.setLocationRelativeTo(null);

this.f.setVisible(true);

}

public static void main(String[] args) {

new Main().display();

}

}






import java.util.Vector;


public class Calc {

private Vector<Student> vector;


public Calc(Vector<Student> vector) {

this.vector = vector;

}

public void calc(){

for(int i = 0 ; i < this.vector.size() ; i++){

Student s = this.vector.get(i);

s.setTot(s.getKor() + s.getEng() + s.getMat() + s.getEdp());

s.setAvg(s.getTot() / 4.);

s.setGrade(this.getGrade(s.getAvg()));

}

}

private char getGrade(double avg){

if(avg <=100 && avg >= 90) return 'A';

else if(avg < 90 && avg >= 80) return 'B';

else if(avg < 80 && avg >= 70) return 'C';

else if(avg < 70 && avg >= 60) return 'D';

else return 'F';

}

}






import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;



public class DBClose {

public static void close(Connection conn){

try{

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

public static void close(Connection conn, Statement stmt){

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

public static void close(Connection conn, Statement stmt, ResultSet rs){

try{

if(rs != null) rs.close();

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

}







import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("D:\\Downloads\\dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

String user = info.getProperty("DBUSER");

String passwd = info.getProperty("DBPASSWORD");

try{

conn = java.sql.DriverManager.getConnection(url, user, passwd);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}






import java.awt.BorderLayout;

import java.awt.Font;

import java.awt.GridLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;

import javax.swing.border.TitledBorder;



public class InputPanel extends JPanel {

private JFrame f;

private JLabel lblHakbun, lblName, lblKor,lblEng, lblMat, lblEdp;

private JTextField tfHakbun, tfName, tfKor, tfEng, tfMat, tfEdp;

private JButton btnContinue, btnBreak;

private Font font;

private JTabbedPane tab;

public InputPanel(JFrame f, JTabbedPane tab) {

this.f = f;

this.tab = tab;

this.font = new Font("NanumGotic", Font.PLAIN, 20);

this.setLayout(new BorderLayout());

this.add("Center", getCenter());

this.add("South", getSouth());

}

private JPanel getSouth(){

JPanel p = new JPanel();

p.add(this.btnContinue = new JButton("입력하기"));

this.btnContinue.setFont(font);

this.btnContinue.addActionListener(

new InputAction(this.f, this.tab, this.tfHakbun, tfName, 

                     this.tfKor, this.tfEng, this.tfMat, this.tfEdp));

p.add(this.btnBreak = new JButton("출력하기"));

this.btnBreak.setFont(font);

this.btnBreak.addActionListener(

new InputAction(this.f, this.tab, this.tfHakbun, tfName, 

                     this.tfKor, this.tfEng,this.tfMat, this.tfEdp));

return p;

}

private JPanel getCenter(){

JPanel p, inner;

inner = new JPanel();

inner.setBorder(new TitledBorder("성적데이터입력"));

inner.setLayout(new GridLayout(6,2,10,10));

inner.add(this.lblHakbun = new JLabel("학번"));

this.lblHakbun.setFont(font);

inner.add(this.tfHakbun = new JTextField(10));

this.tfHakbun.setFont(font);

inner.add(this.lblName = new JLabel("이름"));

this.lblName.setFont(font);

inner.add(this.tfName = new JTextField());

this.tfName.setFont(font);

inner.add(this.lblKor = new JLabel("국어"));

this.lblKor.setFont(font);

inner.add(this.tfKor = new JTextField());

this.tfKor.setFont(font);

inner.add(this.lblEng = new JLabel("영어"));

this.lblEng.setFont(font);

inner.add(this.tfEng = new JTextField());

this.tfEng.setFont(font);

inner.add(this.lblMat = new JLabel("수학"));

this.lblMat.setFont(font);

inner.add(this.tfMat = new JTextField());

this.tfMat.setFont(font);

inner.add(this.lblEdp = new JLabel("전산"));

this.lblEdp.setFont(font);

inner.add(this.tfEdp = new JTextField());

this.tfEdp.setFont(font);

p = new JPanel();

p.add(inner);

return p;

}

}









import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;


public class InputAction implements ActionListener {

private JFrame f;

private JTabbedPane tab;

private JTextField tfHakbun, tfName, tfKor, tfEng, tfMat, tfEdp;

public InputAction(JFrame f, JTabbedPane tab,

JTextField tfHakbun, JTextField tfName, JTextField tfKor,

JTextField tfEng, JTextField tfMat, JTextField tfEdp) {

this.f = f;

this.tab = tab;

this.tfHakbun = tfHakbun;

this.tfName = tfName;

this.tfKor = tfKor;

this.tfEng = tfEng;

this.tfMat = tfMat;

this.tfEdp = tfEdp;

}


@Override

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("입력하기")){

if(!this.check()){

JOptionPane.showMessageDialog(this.f, "입력되지 않은 데이터가 있습니다.", 

"Warning", JOptionPane.WARNING_MESSAGE);

this.tfHakbun.requestFocus();

}else{  //모두 입력했다면

Student s = new Student(this.tfHakbun.getText().trim(), 

                                this.tfName.getText().trim(),

                                Integer.parseInt(this.tfKor.getText().trim()),

                                Integer.parseInt(this.tfEng.getText().trim()),

                                Integer.parseInt(this.tfMat.getText().trim()),

                                Integer.parseInt(this.tfEdp.getText().trim()));

StudentController.insert(s);

JOptionPane.showMessageDialog(this.f, "입력됐습니다.", 

"Success", JOptionPane.INFORMATION_MESSAGE);

this.tfHakbun.setText("");  this.tfName.setText("");

this.tfKor.setText("");  this.tfEng.setText("");

this.tfMat.setText("");  this.tfEdp.setText("");

}

}else if(e.getActionCommand().equals("출력하기")){

this.tab.setSelectedIndex(1);

}

}

private boolean check(){

if(this.tfHakbun.getText().length() == 0 || 

this.tfName.getText().length() == 0 ||

this.tfKor.getText().length() == 0 ||

this.tfEng.getText().length() == 0 ||

this.tfMat.getText().length() == 0 ||

this.tfEdp.getText().length() == 0) return false;

else return true;

}


}







import java.util.Vector;


public class Output {

private Vector<Student> vector;

public Output(Vector<Student> vector) {

this.vector = vector;

}

public void output(){

printLabel();

for(int i = 0 ; i < this.vector.size() ; i++)

System.out.print(this.vector.elementAt(i));

}

private void printLabel(){

System.out.println("                      <<�깆쟻愿�━�꾨줈洹몃옩>>");

}

}





import java.awt.BorderLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.ListSelectionModel;


public class OutputPanel extends JPanel{

private JFrame f;

private JScrollPane pane;

private JTable table;

private JButton btnOriginal, btnCalc, btnSort, btnDelete;

private JPanel p;

OutputPanel(JFrame f) {

this.f = f;

this.p = new JPanel();

this.table = new JTable();

//this.table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

this.btnOriginal = new JButton("원본보기");

this.btnOriginal.addActionListener(new OutputAction(this.f, this.table));

this.btnCalc = new JButton("계산하기");

this.btnCalc.addActionListener(new OutputAction(this.f, this.table));

this.btnSort = new JButton("정렬하기");

this.btnSort.addActionListener(new OutputAction(this.f, this.table));

this.btnDelete = new JButton("삭제하기");

this.btnDelete.addActionListener(new OutputAction(this.f, this.table));

pane = new JScrollPane(this.table, 

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

this.setLayout(new BorderLayout());

this.add("Center", pane);

this.p.add(this.btnOriginal);  this.p.add(this.btnCalc);  this.p.add(this.btnSort);  

this.p.add(this.btnDelete);

this.add("North", p);

}

}





import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JTable;



public class OutputAction implements ActionListener {

private JFrame f;

private JTable table;

OutputAction(JFrame f, JTable table){

this.f = f;

this.table = table;

}

@Override

public void actionPerformed(ActionEvent e) {

switch(e.getActionCommand()){

case "원본보기": viewOriginal(); break;

//case "계산하기": calc(); break;

//case "정렬하기": sort(); break;

//case "삭제하기": delete(); break;

}

}

/*private void delete() {

int [] array = this.table.getSelectedRows();  //1,3,5

for(int i = array.length - 1 ; i >= 0 ; i--){

this.vector.removeElementAt(array[i]);

}

this.sort();

}*/

private void viewOriginal(){  //원본보기

this.table.setModel(new StudentModel(6));

}

/*private void calc(){

Calc calc = new Calc(this.vector);

calc.calc();

this.table.setModel(new StudentModel(this.vector, 9));

}*/

/*private void sort(){

Sort sort = new Sort(this.vector);

sort.sort();

this.table.setModel(new StudentModel(this.vector, 10));

}*/


}






import java.util.Vector;


public class Sort {

private Vector<Student> vector;


public Sort(Vector<Student> vector) {

this.vector = vector;

for(int i = 0 ; i < this.vector.size() ; i++)

this.vector.get(i).setRanking(1);

}

public void sort(){   //��궧���꾪븳 �좏깮�뺣젹

for(int i = 0 ; i < this.vector.size() - 1 ; i++){

for(int j = i +1 ; j < this.vector.size() ; j++){

if(this.vector.get(i).compareTo(this.vector.get(j)) > 0){

this.vector.get(j).setRanking(this.vector.get(j).getRanking() + 1);

}else if(this.vector.get(i).compareTo(this.vector.get(j)) < 0){

this.vector.get(i).setRanking(this.vector.get(i).getRanking() +1);

}

}

}

}

}






import java.sql.Connection;

import java.util.Vector;



public class StudentController {

public static void insert(Student s) {

DBConnection conn = new DBConnection();

conn.loadDriver();

conn.setConnection();

Connection con = conn.getConnection();

StudentDAO.insert(con, s);

DBClose.close(con);

}

public static Vector<Student> select() {

DBConnection conn = new DBConnection();

conn.loadDriver();

conn.setConnection();

Connection con = conn.getConnection();

String sql = "SELECT hakbun, irum, kor, eng, mat, edp ";

sql += " FROM Student";

Vector<Student> vector = StudentDAO.getAllData(con, sql, false);

DBClose.close(con);

return vector;

}

}












import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Vector;



public class StudentDAO {

//원본보기

public static Vector<Student> getAllData(Connection conn, String sql, boolean isFull){

Vector<Student> vector = new Vector<Student>(1,1);

Statement stmt = null;

ResultSet rs = null;

try {

stmt = conn.createStatement();

rs = stmt.executeQuery(sql);

while(rs.next()){

Student s = new Student();

s.setHakbun(rs.getString("hakbun"));

s.setName(rs.getString("irum"));

s.setKor(rs.getInt("kor"));

s.setEng(rs.getInt("eng"));

s.setMat(rs.getInt("mat"));

s.setEdp(rs.getInt("edp"));

if(false){

s.setTot(rs.getInt("tot"));

s.setAvg(rs.getDouble("avg"));

s.setGrade(rs.getString("grade").charAt(0));  //"A" --> 'A'

}

vector.addElement(s);

}

} catch (SQLException e) {

e.printStackTrace();

}

return vector;

}

//학번으로 검색

public static Vector<Student> getOneData(Connection conn, String hakbun){

Vector<Student> vector = new Vector<Student>(1);

Statement stmt = null;   ResultSet rs = null;

try {

stmt = conn.createStatement();

String sql = "SELECT * FROM Student WHERE hakbun = '" + hakbun + "' ";

rs = stmt.executeQuery(sql);

rs.next();

Student s = new Student();

s.setHakbun(rs.getString("hakbun"));

s.setName(rs.getString("irum"));

s.setKor(rs.getInt("kor"));

s.setEng(rs.getInt("eng"));

s.setMat(rs.getInt("mat"));

s.setEdp(rs.getInt("edp"));

vector.addElement(s);

rs.close();

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

return vector;

}

public static void insert(Connection conn, Student s){

Statement stmt = null;

try {

stmt = conn.createStatement();

String sql = "INSERT INTO Student(hakbun, irum, kor, eng, mat, edp) ";

sql += "VALUES('" + s.getHakbun() + "', '" + s.getName() + "', ";

sql += s.getKor() + ", " + s.getEng() + ", " + s.getMat() + ", ";

sql += s.getEdp() + ")";

stmt.executeUpdate(sql);

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}










import java.sql.Connection;

import java.util.Vector;


import javax.swing.table.DefaultTableModel;


public class StudentModel extends DefaultTableModel {

private int choice;

public StudentModel(int choice) {

this.choice = choice;

setModelData();

}

private void setModelData(){

Vector<String> columnVector = new Vector<String>(1,1);

String [] array = {"학번", "이름", "국어", "영어", "수학", "전산", "총점",

                  "평균", "학점", "등수"};

for(int i = 0 ; i < this.choice ; i++)  columnVector.addElement(array[i]);

Vector<Student> dataVector = StudentController.select();

Vector<Object> tableVector = new Vector<Object>(1,1);

for(int i = 0 ; i < dataVector.size() ; i++){

Vector<String> tempVector = new Vector<String>(1,1);

Student s = dataVector.get(i);

tempVector.addElement(s.getHakbun());

tempVector.addElement(s.getName());

tempVector.addElement(String.valueOf(s.getKor()));

tempVector.addElement(String.valueOf(s.getEng()));

tempVector.addElement(String.valueOf(s.getMat()));

tempVector.addElement(String.valueOf(s.getEdp()));

tableVector.addElement(tempVector);

}

this.setDataVector(tableVector, columnVector);

}

}


------------------------------------------------------------------------------

================================================================================

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

전화요금관리프로그램 (찾기기능없음), 

public class CustomerVO {

private int gubun;

private String telnum;

private String irum;

private int howmany;

private int gibon;

private int fee;

private int tax;

private int total;

public CustomerVO(){}

public CustomerVO(int gubun, String telnum, String irum, int howmany) {

this.gubun = gubun;

this.telnum = telnum;

this.irum = irum;

this.howmany = howmany;

}

@Override

public String toString(){

return String.format("%d\t%s\t%s\t%,d\t%,d\t%,d\t%,d",

                   this.gubun, this.telnum, this.irum, this.gibon,

                   this.fee, this.tax, this.total);

}

public int getGubun() {

return gubun;

}

public void setGubun(int gubun) {

this.gubun = gubun;

}

public String getTelnum() {

return telnum;

}

public void setTelnum(String telnum) {

this.telnum = telnum;

}

public String getIrum() {

return irum;

}

public void setIrum(String irum) {

this.irum = irum;

}

public int getHowmany() {

return howmany;

}

public void setHowmany(int howmany) {

this.howmany = howmany;

}

public int getGibon() {

return gibon;

}

public void setGibon(int gibon) {

this.gibon = gibon;

}

public int getFee() {

return fee;

}

public void setFee(int fee) {

this.fee = fee;

}

public int getTax() {

return tax;

}

public void setTax(int tax) {

this.tax = tax;

}

public int getTotal() {

return total;

}

public void setTotal(int total) {

this.total = total;

}

}





import java.util.Scanner;


public class Main {

public static void main(String[] args) {

System.out.println("<<전화요금관리프로그램>>");

Scanner scan = new Scanner(System.in);

Main main = new Main();

int choice = 0;

while(true){

choice = main.showMenu(scan);

if(choice == 4) break;

switch(choice){

case 1 : Input input = new Input(scan);  input.input(); break; 

case 2 : Output output = new Output(); break;

//case 3 :

}

}

System.out.println("Program is over...");

}

int showMenu(Scanner scan){

System.out.println("1:입력, 2:출력, 3:검색, 4:종료");

System.out.print(">> ");

return scan.nextInt();

}

}






import java.util.Scanner;


public class Input {

private Scanner scan;

Input(Scanner scan){

this.scan = scan;

}

void input(){

System.out.print("구분 : ");   int gubun = this.scan.nextInt();

System.out.print("전화번호 : "); String telnum = this.scan.next();

this.scan.nextLine();

System.out.print("성명 : "); String irum = this.scan.nextLine();

System.out.print("통화량 : ");  int howmany = this.scan.nextInt();

this.scan.nextLine();

CustomerVO c = new CustomerVO(gubun, telnum, irum, howmany);

Calc calc = new Calc(c);

CustomerController.insert(c);

}

}








public class Calc {

private CustomerVO c;

Calc(CustomerVO c){

this.c = c;

calc();

}

void calc(){

//1)입력되는 값이 구분이 1이면 영업용, 2이면 관청용, 3이면 가정용이다.

int gibon = (c.getGubun() == 1) ? 6000 :

                 (c.getGubun() == 2) ? 4800 : 3000;

//2)기본요금은 영업용이 6,000원, 관청용이 4,800원, 가정용이 3,000원이다.

//3)통화료는 1통화에 대하여 12원이다.

int fee = c.getHowmany() * 12;

//4)세금은 기본 요금과 통화료를 합한 금액의 10%를 부과한다.

int tax = (int)((gibon + fee) * 0.1);

int total = gibon + fee + tax;

c.setGibon(gibon);

c.setFee(fee);

c.setTax(tax);

c.setTotal(total);

}

}





import java.sql.Connection;

import java.util.Vector;


public class CustomerController {

public static void insert(CustomerVO c){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

CustomerDAO.insert(conn, c);

DBClose.close(conn);

}

public static Vector <CustomerVO> select(){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

Vector<CustomerVO> vector = CustomerDAO.select(conn);

DBClose.close(conn);

return vector;

}

}





import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Vector;



public class CustomerDAO {

public static Vector<CustomerVO> select(Connection conn){

Statement stmt = null;

ResultSet rs = null;

Vector<CustomerVO> vector = new Vector<CustomerVO>(1,1);

try {

stmt = conn.createStatement();

String sql = "SELECT * FROM Telephone";

rs = stmt.executeQuery(sql);

while(rs.next()){

CustomerVO c = new CustomerVO();

c.setGubun(rs.getInt("gubun"));

c.setTelnum(rs.getString("telnum"));

c.setIrum(rs.getString("irum"));

c.setGibon(rs.getInt("gibon"));

c.setFee(rs.getInt("fee"));

c.setTax(rs.getInt("tax"));

c.setTotal(rs.getInt("total"));

vector.addElement(c);

}

rs.close();

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

return vector;

}

public static void insert(Connection conn, CustomerVO c){

Statement stmt = null;

try {

stmt = conn.createStatement();

StringBuffer sb = new StringBuffer("INSERT INTO Telephone ");

sb.append("VALUES('" + c.getTelnum() + "'," + c.getGubun());

sb.append(",'" + c.getIrum() + "'," + c.getHowmany());

sb.append("," + c.getGibon() + "," + c.getFee() + "," + c.getTax());

sb.append("," + c.getTotal() + ")");

//System.out.println(sb.toString());

stmt.executeUpdate(sb.toString());

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}






import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;



public class DBClose {

public static void close(Connection conn){

try{

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

public static void close(Connection conn, Statement stmt){

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

public static void close(Connection conn, Statement stmt, ResultSet rs){

try{

if(rs != null) rs.close();

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

}







import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("D:\\Downloads\\dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

String user = info.getProperty("DBUSER");

String passwd = info.getProperty("DBPASSWORD");

try{

conn = java.sql.DriverManager.getConnection(url, user, passwd);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}





import java.util.Vector;


public class Output {

Output(){

Vector<CustomerVO> vector = CustomerController.select();

for(int i = 0 ; i < vector.size() ; i++){

CustomerVO c = vector.get(i);

System.out.println(c);

}

}

}













자바 네트워크 : UDP

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

import java.text.SimpleDateFormat;

import java.util.Date;


public class UDPTimeServer {

private DatagramSocket server;

private DatagramPacket rPacket, sPacket;

private UDPTimeServer(){

try{

this.server = new DatagramSocket(9999);

System.out.println("Server is ready...");

}catch(SocketException ex){

ex.printStackTrace();

}catch(Exception ex){

ex.printStackTrace();

}

}

private void service(){

String pattern = "지금은 yyyy-MM-dd aa HH:mm:ss 입니다.";

SimpleDateFormat sdf = new SimpleDateFormat(pattern);

try{

while(true){

byte [] buffer = new byte[10];

this.rPacket = new DatagramPacket(buffer, buffer.length);  //받는 패킷

this.server.receive(rPacket);   //수신

InetAddress ia = rPacket.getAddress();  //client 주소

int port = rPacket.getPort();   //client port number

String msg = sdf.format(new Date());

this.sPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, ia, port);

this.server.send(sPacket);   //발송

}

}catch(IOException ex){

ex.printStackTrace();

}

}

public static void main(String[] args) {

new UDPTimeServer().service();

}

}





import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

import java.net.UnknownHostException;



public class UDPTimeClient {

public static void main(String[] args) 

throws SocketException, UnknownHostException, InterruptedException,

IOException {

DatagramSocket client = new DatagramSocket();   

for(int i = 0 ; i < 10 ; i++){

DatagramPacket sPacket = new DatagramPacket("".getBytes(), "".getBytes().length, InetAddress.getByName("localhost"), 9999);  //""를 주어 아무것도 안보냄... 왜그런진 몰라...ㅠㅠ

Thread.sleep(1000);

client.send(sPacket);

byte [] buffer = new byte[512];

DatagramPacket rPacket = new DatagramPacket(buffer, buffer.length);

client.receive(rPacket);

String msg = new String(buffer, 0, rPacket.getLength());

System.out.println(msg);

}

client.close();

}

}

출력:

지금은 2014-04-03 AM 10:33:23 입니다.

지금은 2014-04-03 AM 10:33:24 입니다.

지금은 2014-04-03 AM 10:33:25 입니다.

지금은 2014-04-03 AM 10:33:26 입니다.

지금은 2014-04-03 AM 10:33:27 입니다.

지금은 2014-04-03 AM 10:33:28 입니다.

지금은 2014-04-03 AM 10:33:29 입니다.

지금은 2014-04-03 AM 10:33:30 입니다.

지금은 2014-04-03 AM 10:33:31 입니다.

지금은 2014-04-03 AM 10:33:32 입니다.

----------------------------------------------------------

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.SocketException;


public class UDPServer {

private DatagramSocket server;

private DatagramPacket rPacket, sPacket;

UDPServer(){

try{

this.server = new DatagramSocket(9999);

System.out.println("Server is ready...");

}catch(SocketException ex){

ex.printStackTrace();

}

}

private void service(){

try{

while(true){

byte [] buffer = new byte[512];

this.rPacket = new DatagramPacket(buffer, buffer.length);

this.server.receive(rPacket);

String msg = new String(buffer, 0, rPacket.getLength());

if(msg.equals("bye")) break;

System.out.println("Client 로 부터 받은 문자열 : " + msg);

this.sPacket = new DatagramPacket(

msg.getBytes(), msg.getBytes().length, 

rPacket.getAddress(), rPacket.getPort());

this.server.send(sPacket);

}

}catch(Exception ex){

ex.printStackTrace();

}finally{

System.out.println("Server is closed...");

try{

this.server.close();

}catch(Exception ex){}

}

}

public static void main(String[] args) {

new UDPServer().service();

}

}





import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

import java.util.Scanner;



public class UDPClient {

private DatagramSocket client;

private DatagramPacket rPacket, sPacket;

private Scanner scan;

UDPClient() {

try{

this.client = new DatagramSocket();

this.scan = new Scanner(System.in);

System.out.println("발송준비완료");

}catch(SocketException ex){

ex.printStackTrace();

}

}

private void service(){

String line = null;

try{

while(true){

System.out.print(">> ");

line = this.scan.nextLine();

if(line == null || line.equals("bye")){

line = "bye";

break;

}

this.sPacket = new DatagramPacket(line.getBytes(), line.getBytes().length,

                       InetAddress.getByName("localhost"), 9999);

this.client.send(sPacket);  //서버로 발송

byte [] buffer = new byte[512];

this.rPacket = new DatagramPacket(buffer, buffer.length);

this.client.receive(rPacket);

String msg = new String(buffer, 0, rPacket.getLength());

System.out.println("서버로부터 들어온 문자열 : " + msg);

}

}catch(Exception ex){

ex.printStackTrace();

}finally{

try{

this.client.close();

}catch(Exception ex){}

}

}

public static void main(String[] args) {

new UDPClient().service();

}

}

출력:

java UDPClient

발송준비완료

>> 헤헷

서버로부터 들어온 문자열 : 헤헷

>> 으음..

서버로부터 들어온 문자열 : 으음..

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

NIO

Byte Buffer

import java.nio.ByteBuffer;

// position <= limit <= capacity

public class BufferDemo {

public static void main(String[] args) {

ByteBuffer bb = ByteBuffer.allocate(12);  //12바이트로 만들어줌.

System.out.println(bb);  //처음에 position은 0, limit와 capacity는 12

bb.putInt(100);  //100이 4바이트를 차지하니, 포지션 4이동.

System.out.println(bb);  

bb.putDouble(89.5);  //더블형 8바이트가 들어왓으니 포지션 12.

System.out.println(bb);  

//bb.put((byte)5);  //오류발생. 포지션이 리미트를 넘어감

bb.rewind();  //position이 처음위치 0으로이동

System.out.println(bb);    

System.out.println(bb.getInt());

System.out.println(bb);

System.out.println(bb.getDouble());

System.out.println(bb);

}

}

출력:

java.nio.HeapByteBuffer[pos=0 lim=12 cap=12]

java.nio.HeapByteBuffer[pos=4 lim=12 cap=12]

java.nio.HeapByteBuffer[pos=12 lim=12 cap=12]

java.nio.HeapByteBuffer[pos=0 lim=12 cap=12]

100

java.nio.HeapByteBuffer[pos=4 lim=12 cap=12]

89.5

java.nio.HeapByteBuffer[pos=12 lim=12 cap=12]

----------------------

import java.nio.ByteBuffer;

public class BufferDemo {

public static void main(String[] args) {

ByteBuffer bb = ByteBuffer.allocate(12);  //12바이트로 만들어줌.

System.out.println(bb);  //처음에 position은 0, limit와 capacity는 12

bb.putInt(100);  //100이 4바이트를 차지하니, 포지션 4이동.

System.out.println(bb);

bb.flip();  //psition을 0으로 옮기고, 원래 position의 값은 lim로 바꿔줌.

System.out.println(bb);

}

}

출력:

java.nio.HeapByteBuffer[pos=0 lim=12 cap=12]

java.nio.HeapByteBuffer[pos=4 lim=12 cap=12]

java.nio.HeapByteBuffer[pos=0 lim=4 cap=12]

-----------------------------------------------------------

Int Buffer

import java.nio.IntBuffer;


public class BufferDemo1 {

public static void main(String[] args) {

IntBuffer ib = IntBuffer.allocate(10);  //int형으로 10칸할당해주어서 40바이트. 한칸당4바이트.

System.out.println(ib);

ib.put(4).put(5).put(6).put(7).put(8).put(9);

System.out.println(ib);

ib.flip();  //position은 0으로, 마지막 position의 위치를 limit로.

System.out.println(ib);

while(ib.hasRemaining()){  //ib의 값이 있을 때까지

System.out.print(ib.get() + ",");

}

}

}

출력:

java.nio.HeapIntBuffer[pos=0 lim=10 cap=10]

java.nio.HeapIntBuffer[pos=6 lim=10 cap=10]

java.nio.HeapIntBuffer[pos=0 lim=6 cap=10]

4,5,6,7,8,9,

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

속도측정 - IO

import java.io.IOException;


public class Main {

public static void main(String[] args) throws IOException{

FullBuffer.start();

FullBuffer.copy("/home/mino/Downloads/staruml.exe", "/home/mino/Temp/staruml.exe" );

FullBuffer.end();

long differ = FullBuffer.during();

System.out.println(differ + " ms");

}

}

위에 메인에서만 FullBuffer를 SmallBuffer, NonBuffer로 바꿔주어 실행해 보면 아래의 결과값.


버퍼링을 하지 않을때

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;


public class NonBuffer {

private static long start;

private static long end;

public static void start()  { start = System.currentTimeMillis(); }

public static void end()  { end = System.currentTimeMillis();  }

public static long during() { return end - start; }

public static void copy(String source, String target) throws IOException {

FileInputStream fis = new FileInputStream(source);

FileOutputStream fos = new FileOutputStream(target);

int su = 0 ;

while((su = fis.read()) != -1){

fos.write(su);

}

System.out.println("Copy End...");

}

}

출력:

Copy End...

42508 ms


버퍼링을 살짝 할때

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;


public class SmallBuffer {

private static long start;

private static long end;

public static void start()  { start = System.currentTimeMillis(); }

public static void end()  { end = System.currentTimeMillis();  }

public static long during() { return end - start; }

public static void copy(String source, String target) throws IOException {

FileInputStream fis = new FileInputStream(source);

FileOutputStream fos = new FileOutputStream(target);

int count = 0;

byte [] buffer = new byte[1024];

while((count = fis.read(buffer)) != -1){

fos.write(buffer, 0, count);

}

System.out.println("Copy End...");

}

}

출력:

Copy End...

88 ms


버퍼링을 완전 쓸때

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;


public class FullBuffer {

private static long start;

private static long end;

public static void start()  { start = System.currentTimeMillis(); }

public static void end()  { end = System.currentTimeMillis();  }

public static long during() { return end - start; }

public static void copy(String source, String target) throws IOException {

FileInputStream fis = new FileInputStream(source);

FileOutputStream fos = new FileOutputStream(target);

int count = 0;

byte [] buffer = new byte[fis.available()];

while((count = fis.read(buffer)) != -1){

fos.write(buffer, 0, count);

}

System.out.println("Copy End...");

}

}

출력:

Copy End...

57 ms


NIO로 했을때 

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.FileChannel.MapMode;


public class FileChannelDemo {

private static long start;

private static long end;

public static void start()  { start = System.currentTimeMillis(); }

public static void end()  { end = System.currentTimeMillis();  }

public static long during() { return end - start; }

public static void copy(String source, String target) throws IOException {

FileInputStream fis = new FileInputStream(source);

FileOutputStream fos = new FileOutputStream(target);

FileChannel in = fis.getChannel();

FileChannel out = fos.getChannel();

MappedByteBuffer map = in.map(MapMode.READ_ONLY, 0, in.size()); //처음부터 파일채널의 사이즈만큼 읽어서

out.write(map);

System.out.println("Copy End...");

}

}

출력:

Copy End...

82 ms


in을 기준으로 transferTo를 써서 

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.FileChannel.MapMode;


public class FileChannelDemo1 {

private static long start;

private static long end;

public static void start()  { start = System.currentTimeMillis(); }

public static void end()  { end = System.currentTimeMillis();  }

public static long during() { return end - start; }

public static void copy(String source, String target) throws IOException {

FileInputStream fis = new FileInputStream(source);

FileOutputStream fos = new FileOutputStream(target);

FileChannel in = fis.getChannel();

FileChannel out = fos.getChannel();

in.transferTo(0, in.size(), out);  //0~사이즈만큼 out 채널로 보냄.

System.out.println("Copy End...");

}

}

출력:

Copy End...

18 ms

output을 기준으로 transferFrom 사용

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.channels.FileChannel;



public class FileChannelDemo2 {

private static long start;

private static long end;

public static void start()  { start = System.currentTimeMillis(); }

public static void end()  { end = System.currentTimeMillis();  }

public static long during() { return end - start; }

public static void copy(String source, String target) throws IOException {

FileInputStream fis = new FileInputStream(source);

FileOutputStream fos = new FileOutputStream(target);

FileChannel in = fis.getChannel();

FileChannel out = fos.getChannel();

out.transferFrom(in, 0, in.size());

System.out.println("Copy End...");

}

}

출력:

Copy End...

23 ms

//transferFrom을 쓰면 가장빠르다는데.. 왜 난 transferTo가 더빠르지..?

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

===================================================================

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ


                JDBC      

미리준비한 offic txt와 img파일을 vm윈도우로 옮겨줌.

데몬으로 설치해주고. Customize 선택해서 access 체크된것만 확인. 그리고 인스톨.

우편번호 다운. http://www.epost114.co.kr/ . 우편번호 다운로드 클릭.

우정사업본부 고시 우편번호 DB (현재 사용되고 있는 전체 우편번호 DB임) 다운로드.

실행하면 풀리면서 c:에 우편번호파일 폴더가 생김.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

ODBC 설정. Control Panel\All Control Panel Items\Administrative Tools\ODBC Data Sources 들어가서

System DSN 탭에서 Add눌러서 .mdb or .accdb 택하고 확인. data source name에 이름(난 access) 써주고(ODBC 이름), 데이터베이스 선택 을 눌러서 사용할 액세스파일을 지정해줌. 확인 확인

아이디와 암호를 줄것이라면system DSN에서 아까만든 access를 configure 누른 후 오른쪽 advanced 누르면 아이디 비번을 정해줄 수 있다. 아디scott, 비번tiger  해줌.

그리고 이클립스에서 window- other perspective 에서 sql Explorer 선택.

new-connection profile에서 name은 아무거나, Driver는 jdbc odbc bridget 해주고 URL : jdbc:odbc:access(access는 아까정한 odbc이름). User는 아무거나.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

우편번호 검색


// 1. import하자

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class JDBCDemo {

private static final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";

private static final String URL = "jdbc:odbc:access";  //ODBC name

public static void main(String[] args) {

//2. Driver Loading

try{

Class.forName(DRIVER);

System.out.println("Driver loading Success");

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

//3. Database Connection

Connection conn = null;

try{

conn = DriverManager.getConnection(URL);  //원래 아이디 비번도 같이 써줘야 하는데 우린 설정을 안해서 안넣음.

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connect failure");

}

//4. Statement 객체 생성

Statement stmt = null;

ResultSet rs = null;  //결과를 가져올 때 사용

Scanner scan = new Scanner(System.in);

System.out.print("찾고자 하시는 동/읍/면 이름 : ");

String dongName = scan.nextLine().trim();

try{

stmt = conn.createStatement();

//5. Query 실행

String sql = "SELECT zipcode, sido, gugun, dong ";  //마지막 dong뒤에는 띄어야함.

sql += "FROM zipcode WHERE dong LIKE '%" + dongName + "%'";  //문자열이 데이터베이스는 '', 자바는"

rs = stmt.executeQuery(sql);  //결과값을 resultset에 넣어줌.

//6. Query 결과 수행

while(rs.next()){

String zipcode = rs.getString(1);  //JDBC는 인덱스가 1부터 시작.

String sido = rs.getString("sido");  //몇번짼지모르면 이름으로 불러와도됨.

String gugun = rs.getString("gugun");

String dong = rs.getString("dong");

System.out.printf("(%s) %s %s %s\n", zipcode, sido, gugun, dong);

}

rs.close();

stmt.close();

}catch(SQLException ex){

ex.printStackTrace();

}

//7.DB Close

try{  //닫는건 거꾸로

if(rs != null) conn.close();

}catch(SQLException ex){}

}

}

출력:
Driver loading Success
Connection Success
찾고자 하시는 동/읍/면 이름 : 상하
(446917) 경기도 용인시 기흥구 상하동
(446568) 경기도 용인시 기흥구 상하동
(446918) 경기도 용인시 기흥구 상하동
(446918) 경기도 용인시 기흥구 상하동
(446519) 경기도 용인시 기흥구 상하동
(446518) 경기도 용인시 기흥구 상하동
(446517) 경기도 용인시 기흥구 상하동
(446514) 경기도 용인시 기흥구 상하동
(446513) 경기도 용인시 기흥구 상하동
(446512) 경기도 용인시 기흥구 상하동
(446719) 경기도 용인시 기흥구 상하동
(446914) 경기도 용인시 기흥구 상하동
(446774) 경기도 용인시 기흥구 상하동
(446773) 경기도 용인시 기흥구 상하동
(446775) 경기도 용인시 기흥구 상하동
(446942) 경기도 용인시 기흥구 상하동
(446516) 경기도 용인시 기흥구 상하동
(446515) 경기도 용인시 기흥구 상하동
(446581) 경기도 용인시 기흥구 상하동
(446769) 경기도 용인시 기흥구 상하동
(585911) 전라북도 고창군 상하면
(585912) 전라북도 고창군 상하면
(585911) 전라북도 고창군 상하면
(585913) 전라북도 고창군 상하면
(585914) 전라북도 고창군 상하면
(585912) 전라북도 고창군 상하면
(585914) 전라북도 고창군 상하면
(585914) 전라북도 고창군 상하면
(585913) 전라북도 고창군 상하면
(585910) 전라북도 고창군 상하면
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
메모장을 열어 아래와 같이 적어서 저장해줌. dbinfo.properties 로 모든파일로 저장해서 d: downloads폴더에 저장.
DBDRIVER=sun.jdbc.odbc.JdbcOdbcDriver
DBURL=jdbc:odbc:access
DBUSER=scott
DBPWD=tiger


import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

public class JdbcSwing {
private JFrame f;
private JTextField tf;
private Container con;
private JTable table;
private JScrollPane pane;
private JdbcSwing(){
this.f = new JFrame("우편번호검색 프로그램");
this.con = this.f.getContentPane();
this.table = new JTable();
this.pane = new JScrollPane(this.table, 
                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
                     JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.tf = new JTextField();
}
private void display(){
this.con.setLayout(new BorderLayout());
this.tf.addActionListener(new ZipcodeController(this.f, this.table, this.tf));
this.con.add("North", this.tf);
this.con.add("Center", this.pane);
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.f.setSize(800,400);
this.f.setVisible(true);
}
public static void main(String[] args) {
new JdbcSwing().display();
}
}




import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JTextField;

public class ZipcodeController implements ActionListener{
private JFrame f;
private JTable table;
private JTextField tf;
public ZipcodeController(JFrame f, JTable table, JTextField tf) {
this.f = f;
this.table = table;
this.tf = tf;
}

@Override
public void actionPerformed(ActionEvent evt){
ZipcodeModel zm = new ZipcodeModel(this.f, this.tf.getText());
this.table.setModel(zm);
System.out.println(this.tf.getText());
}
}






import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class ZipcodeModel extends DefaultTableModel{
private JFrame f;
private String dongName;
private Connection conn;
public ZipcodeModel(JFrame f, String dongName) {
this.f = f;
this.dongName = dongName;
Properties props = new Properties();
try{
props.load(new FileInputStream(new File("D:\\downloads\\dbinfo.properties")));
Class.forName(props.getProperty("DBDRIVER"));  //driver loading
this.conn = DriverManager.getConnection(props.getProperty("DBURL"),
                                      props.getProperty("DBUSER"),
                                      props.getProperty("DBPWD"));
JOptionPane.showMessageDialog(this.f, "Driver Loading & Connection Success");
}catch(ClassNotFoundException ex){
JOptionPane.showMessageDialog(this.f, "Class Not Found");
}catch(IOException ex){
JOptionPane.showMessageDialog(this.f, ex.getMessage());
}catch(SQLException ex){
JOptionPane.showMessageDialog(this.f, ex.getMessage());
}
this.getData();
}
private void getData(){
Statement stmt = null;
ResultSet rs = null;
Vector<Object> dataVector = new Vector<Object>(1,1);
String [] array = {"우편번호", "시도", "시군구", "읍면동", "리", "번지", "나머지주소"};
Vector<String> columnVector = new Vector<String>(1,1);
for(String str : array)  columnVector.addElement(str);
try{
stmt = this.conn.createStatement();
StringBuffer sb = new StringBuffer("SELECT zipcode, sido, gugun, dong, ri,");
sb.append("bunji, etc FROM zipcode WHERE dong LIKE '%");
sb.append(this.dongName + "%' ");
rs = stmt.executeQuery(sb.toString());
if(!rs.next()){
JOptionPane.showMessageDialog(this.f, "데이타가 없습니다.");
return;
}
do{
Vector<String> temp = new Vector<String>(1,1);
String zipcode = rs.getString("zipcode");  temp.addElement(zipcode);
String sido = rs.getString("sido");  temp.addElement(sido);
String gugun = rs.getString("gugun"); temp.addElement(gugun);
String dong = rs.getString("dong"); temp.addElement(dong);
String ri = rs.getString("ri");   if(ri == null) ri = "";
temp.addElement(ri);
String bunji = rs.getString("bunji");   if(bunji == null) bunji ="";
temp.addElement(bunji);
String etc = rs.getString("etc");   if(etc == null) etc = "";
temp.addElement(etc);
dataVector.addElement(temp);
}while(rs.next());
rs.close();
stmt.close();
this.conn.close();
}catch(SQLException ex){
JOptionPane.showMessageDialog(this.f, ex.getMessage());
}
this.setDataVector(dataVector, columnVector);
}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

centos 설치(오늘은 다운만)

www.centos.org 접속. get centos linux now 선택. download now 선택. 

http://ftp.daum.net/centos/6.5/isos/x86_64/CentOS-6.5-x86_64-bin-DVD1.iso  선택(빠른 것 아무거나 받아도됭)



import java.net.MalformedURLException;

import java.net.URL;

import java.util.Scanner;

//1. MalformedURLException를 이용해서 URL Parsing

public class URLDemo {

public static void main(String[] args) {

URLDemo ud = new URLDemo();

String urlStr = ud.getURL();

URL url = null;

try{

url = new URL(urlStr);

System.out.println("protocol : " + url.getProtocol());

System.out.println("hostname : " + url.getHost());

System.out.println("file : " + url.getPath() + url.getFile());

System.out.println("query string : " + url.getQuery());

System.out.println("port number : " + url.getPort());

System.out.println("default port number : " + url.getDefaultPort());

}catch(MalformedURLException ex){

System.out.println(ex.getMessage());

}

}

String getURL(){

System.out.print("URL : ");

Scanner scan = new Scanner(System.in);

return scan.next().trim();

}

}

출력:

URL : http://www.naver.com/index.html : 80

protocol : http

hostname : www.naver.com

file : /index.html/index.html

query string : null

port number : -1

default port number : 80

출력:

URL : http://software.naver.com/software/summary.nhn?softwareId=MFS_100040

protocol : http

hostname : software.naver.com

file : /software/summary.nhn/software/summary.nhn?softwareId=MFS_100040

query string : softwareId=MFS_100040

port number : -1

default port number : 80

출력:

URL : file:///home/mino/Downloads/sungjuk_utf8.dat

protocol : file

hostname : 

file : /home/mino/Downloads/sungjuk_utf8.dat/home/mino/Downloads/sungjuk_utf8.dat

query string : null

port number : -1

default port number : -1

--------------------------------------------------------------

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

//2. openStream() 을 이용해서 InputStream 객체 생성

public class URLDemo1 implements ActionListener {

private JFrame f;

private JTextArea area;

private JScrollPane scroll;

private JTextField tf;

private Container con;

private URLDemo1(){

this.f = new JFrame("My Browser");

this.con = this.f.getContentPane();

this.area = new JTextArea();

this.scroll = new JScrollPane(area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

                      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

this.tf = new JTextField("http://", JTextField.LEFT);

this.tf.addActionListener(this);

}

private void display(){

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.con.setLayout(new BorderLayout());

this.con.add("North", this.tf);

this.con.add("Center", this.scroll);

this.f.setSize(700, 500);

this.f.setVisible(true);

}

@Override

public void actionPerformed(ActionEvent evt){

URL url = null;

BufferedReader br = null;

try{

url = new URL(this.tf.getText().trim());

InputStream is = url.openStream();

br = new BufferedReader(new InputStreamReader(is));

String line = null;

while((line = br.readLine()) != null){

this.area.append(line + "\n");

}

} catch(MalformedURLException ex){

JOptionPane.showMessageDialog(this.f, ex.getMessage());

} catch(IOException ex){

JOptionPane.showMessageDialog(this.f, ex.getMessage());

} finally{

try{

br.close();

} catch(IOException ex){}

}

}

public static void main(String[] args) {

new URLDemo1().display();

}

}

출력은 텍스트필드에 www.naver.com을 치면 그 화면에 html내용을 다 읽어들인다.

----------------위 코드를 파일 출력

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.MalformedURLException;

import java.net.URL;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

//2. openStream() 을 이용해서 InputStream 객체 생성

public class URLDemo1 implements ActionListener {

private JFrame f;

private JTextArea area;

private JScrollPane scroll;

private JTextField tf;

private Container con;

private URLDemo1(){

this.f = new JFrame("My Browser");

this.con = this.f.getContentPane();

this.area = new JTextArea();

this.scroll = new JScrollPane(area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

                      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

this.tf = new JTextField("http://", JTextField.LEFT);

this.tf.addActionListener(this);

}

private void display(){

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.con.setLayout(new BorderLayout());

this.con.add("North", this.tf);

this.con.add("Center", this.scroll);

this.f.setSize(700, 500);

this.f.setVisible(true);

}

@Override

public void actionPerformed(ActionEvent evt){

URL url = null;

BufferedReader br = null;

PrintWriter pw = null;

try{

url = new URL(this.tf.getText().trim());

InputStream is = url.openStream();

br = new BufferedReader(new InputStreamReader(is));

String hostname = url.getHost();   //www.naver.com

hostname = hostname.substring(4, hostname.lastIndexOf("."));

pw = new PrintWriter(new BufferedWriter(new FileWriter(new File(hostname + ".txt"))));

String line = null;

while((line = br.readLine()) != null){

this.area.append(line + "\n");

pw.println(line);

pw.flush();

}

JOptionPane.showMessageDialog(this.f, "잘 저장됐습니다.");

} catch(MalformedURLException ex){

JOptionPane.showMessageDialog(this.f, ex.getMessage());

} catch(IOException ex){

JOptionPane.showMessageDialog(this.f, ex.getMessage());

} finally{

try{

br.close();  pw.close();

} catch(IOException ex){}

}

}

public static void main(String[] args) {

new URLDemo1().display();

}

}

//출력은 www.naver.com 을 치면 naver.txt로 저장됨. 

----------------------------------------------------

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Scanner;

import java.util.Set;


//3. URL 의 openConnection() 을 이용해서 URLConnection 객체 생성


public class URLConnectionDemo {

public static void main(String[] args) {

String urlStr = new URLConnectionDemo().getURL();

URL url = null;

URLConnection conn = null;

try{

url = new URL(urlStr);

conn = url.openConnection();

Map<String, List<String>> map = conn.getHeaderFields();

Set<String> set = map.keySet();

Iterator<String> iters = set.iterator();

while(iters.hasNext()){

String key = iters.next();

System.out.print(key +" --> ");

List<String> list = map.get(key);

for(int i = 0 ; i < list.size() ; i++){

System.out.print(list.get(i) +", ");

}

System.out.println();

}

}catch(MalformedURLException ex){

}catch(IOException ex){}

}

String getURL(){

System.out.print("URL : ");

Scanner scan = new Scanner(System.in);

return scan.next().trim();

}

}

출력:

URL : http://www.naver.com

null --> HTTP/1.1 200 OK, 

Vary --> Accept-Encoding,User-Agent, 

Transfer-Encoding --> chunked, 

Date --> Wed, 02 Apr 2014 01:39:17 GMT, 

P3P --> CP="CAO DSP CURa ADMa TAIa PSAa OUR LAW STP PHY ONL UNI PUR FIN COM NAV INT DEM STA PRE", 

Connection --> close, 

Content-Type --> text/html; charset=UTF-8, 

Server --> nginx, 

Pragma --> no-cache, 

Cache-Control --> no-cache, no-store, must-revalidate, 

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

URL Encoder

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.util.Scanner;



public class URLEncoderDemo {

public static void main(String[] args) throws UnsupportedEncodingException {

String str = new URLEncoderDemo().getString();

String en = URLEncoder.encode(str, "KSC5601");

System.out.printf("%s --> %s\n", str, en);

}

String getString(){

System.out.print("Encoding 할 문자열 : ");

Scanner scan = new Scanner(System.in);

return scan.next().trim();

}

}

출력:

Encoding 할 문자열 : 안녕하세요

안녕하세요 --> %BE%C8%B3%E7%C7%CF%BC%BC%BF%E4

-----------------------------------------

URL Decoder

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;

import java.util.Scanner;


public class URLDecoderDemo {

public static void main(String[] args) throws UnsupportedEncodingException {

String str = new URLDecoderDemo().getString();

String de = URLDecoder.decode(str, "KSC5601");

System.out.printf("%s --> %s\n", str, de);

}

String getString(){

System.out.print("Decoding 할 문자열 : ");

Scanner scan = new Scanner(System.in);

return scan.next().trim();

}

}

출력:

Decoding 할 문자열 : %BE%C8%B3%E7%C7%CF%BC%BC%BF%E4

%BE%C8%B3%E7%C7%CF%BC%BC%BF%E4 --> 안녕하세요

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

TCP

Server

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.ServerSocket;

import java.net.Socket;


public class TcpDemo {

private ServerSocket server;

private Socket client;

private TcpDemo(){

this.server = null;

try{

this.server = new ServerSocket(8080);

System.out.println("Server is just started...");

}catch(IOException ex){

System.out.println(ex.getMessage());

}

}

private void service(){

BufferedReader br = null;

try{

this.client = this.server.accept();

System.out.println("[" + this.client.getInetAddress().getHostAddress() + "] 접속성공");

InputStream is = this.client.getInputStream();

String line = null;

br = new BufferedReader(new InputStreamReader(is));

while((line = br.readLine()) != null){

System.out.println(line);

}

}catch(IOException ex){

System.out.println(ex.getMessage());

}finally{

try{

this.client.close();

br.close();

}catch(IOException ex){}

}

}

public static void main(String[] args) {

new TcpDemo().service();

}

}

//쓰레드를 안만들어서 동시성이없다. 쓰레드를 만들어야함.

출력: 웹페이지에서 http://localhost:8080 입력. or http://Ubuntu-22:8080 (Ubuntu-22는 내 컴퓨터이름)

Server is just started...

[127.0.0.1] 접속성공

GET / HTTP/1.1

Host: ubuntu-22:8080

Connection: keep-alive

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36

Accept-Encoding: gzip,deflate,sdch

Accept-Language: en-US,en;q=0.8

출력: 웹페이지에서 http://localhost:8080/abc/def/ghi.test.html  입력.

Server is just started...

[127.0.0.1] 접속성공

GET /abc/def/ghi.test.html HTTP/1.1

Host: localhost:8080

Connection: keep-alive

Cache-Control: max-age=0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36

Accept-Encoding: gzip,deflate,sdch

Accept-Language: en-US,en;q=0.8

//접속해서 들어온 클라이언트의 정보를 알 수 있다. 크롬으로 접속했으며등등~~


--------------------------------내보낼때

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;


public class TcpDemo {

private ServerSocket server;

private Socket client;

private TcpDemo(){

this.server = null;

try{

this.server = new ServerSocket(8080);

System.out.println("Server is just started...");

}catch(IOException ex){

System.out.println(ex.getMessage());

}

}

private void service(){

BufferedReader br = null;

PrintWriter pw = null;

try{

this.client = this.server.accept();

System.out.println("[" + this.client.getInetAddress().getHostAddress() + "] 접속성공");

InputStream is = this.client.getInputStream();

String line = null;

br = new BufferedReader(new InputStreamReader(is));

line = br.readLine(); //GET /index.html HTTP/1.1

int start = line.indexOf(" "); //3

int last = line.lastIndexOf("HTTP"); //16

line = line.substring(start +2, last);  //index.html 만 뽑기 위해서

String filename = null;

if(line.length() == 1) filename = "index.html";

else filename = line;

//System.out.println(filename);

OutputStream os = this.client.getOutputStream();  //client로 전송할 객체

File file = new File(filename);

pw = new PrintWriter(new OutputStreamWriter(os));

br = null;

br = new BufferedReader(new FileReader(file));

line = null;

while((line = br.readLine()) != null){  //index.html파일로부터 읽기

pw.println(line);

pw.flush();

}

while(line = p)

}catch(IOException ex){

System.out.println(ex.getMessage());

}finally{

try{

this.client.close();

br.close();

pw.close();

}catch(IOException ex){}

}

}

public static void main(String[] args) {

new TcpDemo().service();

}

}

그리고 다른컴퓨터에서 html파일로 아래와 같이 만들어서 이름을 index.html 로 주고 tcp.class와 같은 폴더에 저장한다.

<html>

 <head>

  <meta charset="UTF-8">

  <title>Welcome! my hompage...</title>

 </head>

 <body bgcolor='yellow'>

    <font size='7' color='red'><b>Hello, World</font>

 </body>

</html>

실행시키면 노랑바탕에 빨강 글씨로 나온다. 

그리고 서버를 열고.....

이제 내컴퓨터에서 웹페이지에서 접속할 아이피:8080 을 쓰면 index.html 페이지가 열린다

---------------------------------------------------------------

쓰레드까지 추가. 그러면 여러번 한번접속후 종료하지않고 계속 받을 수 있음.

import java.io.BufferedReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;


public class Apache {

private ServerSocket server;

private Socket client;

Apache(){

try{

this.server = new ServerSocket(8081);

System.out.println("Server is ready...");

while(true){

this.client = this.server.accept();

ClientThread ct = new ClientThread(this.client);

ct.start();

}

}catch(Exception ex){

System.out.println(ex.getMessage());

}

}

public static void main(String[] args) {

new Apache();

}

}





import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.Socket;


public class ClientThread extends Thread {

private Socket client;

private BufferedReader br;

private PrintWriter pw;

ClientThread(Socket client){

this.client = client;

try {

InputStream is = this.client.getInputStream();

OutputStream os = this.client.getOutputStream();

this.br = new BufferedReader(new InputStreamReader(is));

this.pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os)));

} catch (Exception e) {

System.out.println(e.toString());

}

@Override

public void run(){

//Thread 가 해야할 일

try{

String line = this.br.readLine();   //GET /index.html HTTP/1.1

int start = line.indexOf(" ");  //3

int last = line.lastIndexOf("HTTP");  //16

line = line.substring(start + 2, last);   //index.html

String filename = null;

if(line.length() == 1)  filename = "index.html";

else filename = line;

//파일을 읽을 BufferedReader

BufferedReader brTemp = 

new BufferedReader(new FileReader(new File(filename)));

line = null;

while((line = brTemp.readLine()) != null){  //파일로 부터 한 줄씩 읽어서

this.pw.println(line);

this.pw.flush();

}

brTemp.close();

}catch(Exception ex){

ex.printStackTrace();

}finally{

try{

if(this.br != null) this.br.close();

if(this.pw != null) this.pw.close();

}catch (Exception e) {

e.printStackTrace();

}

}

}

}


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

TCP 서버 클라이언트 : 잘 전송되는지 확인.

import java.io.BufferedReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;



public class TcpServer {

private ServerSocket server;

private Socket client;

private BufferedReader br;

private PrintWriter pw;

private TcpServer(){

try{

this.server = new ServerSocket(8888);

System.out.println("Server is ready...");

}catch(Exception ex){

ex.printStackTrace();

}

}

private void service(){

try{

while(true){

this.client = this.server.accept();

System.out.println(

"[" + this.client.getInetAddress().getHostAddress() + "] 님이 연결됐습니다." );

TcpThread tt = new TcpThread(this.client);

tt.start();

}

}catch(Exception ex){

ex.printStackTrace();

}finally{

System.out.println("Server is closed...");

try{

this.server.close();

}catch(Exception ex){

ex.printStackTrace();

}

}

}

public static void main(String[] args) {

new TcpServer().service();

}

}






import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.Socket;


public class TcpThread extends Thread{

private Socket client;

private BufferedReader br;

private PrintWriter pw;

TcpThread(Socket client){

this.client = client;

try{

this.br = new BufferedReader(

new InputStreamReader(this.client.getInputStream()));

this.pw = new PrintWriter(

new BufferedWriter(

new OutputStreamWriter(this.client.getOutputStream())));

}catch(Exception ex){

ex.printStackTrace();

}

}

@Override

public void run(){

//Thread 가 해야할 일

try{

String line = null;

while(true){

line = this.br.readLine();

if(line.equals("quit")) break;

System.out.println("String from Client : " + line);

this.pw.println(line);

this.pw.flush();

}

}catch(Exception ex){

ex.printStackTrace();

}finally{

try{

this.br.close();

this.pw.close();

}catch(Exception ex){

ex.printStackTrace();

}

}

}

}







import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.Socket;

import java.util.Scanner;



public class TcpClient {

private Socket socket;

private Scanner scan;

private String ip;

private int port;

private BufferedReader br;

private PrintWriter pw;

TcpClient(){

try{

this.scan = new Scanner(System.in);

this.getServerInfo();

this.socket = new Socket(ip, port);

System.out.println("[" + this.ip + "] connected...");

this.br = new BufferedReader(

new InputStreamReader(this.socket.getInputStream()));

this.pw = new PrintWriter(

new BufferedWriter(

new OutputStreamWriter(this.socket.getOutputStream())));

}catch(Exception ex){

ex.printStackTrace();

}

}

private void service(){

try{

String line = null;

while(true){

System.out.print("서버에 보낼 문자열 : ");

line = this.scan.nextLine().trim();

if(line == null || line.equals("quit")) {

this.pw.println("quit");

this.pw.flush();

break;

}

this.pw.println(line);

this.pw.flush();    //서버로 발송

System.out.println("서버로 부터 들어온 문자열 : " + this.br.readLine());

//서버에서 들어온 문자열

}

}catch(Exception ex){

ex.printStackTrace();

}finally{

try{

this.br.close();

this.pw.close();

}catch(Exception ex){

ex.printStackTrace();

}

}

}

public static void main(String[] args) {

TcpClient tc = new TcpClient();

tc.service();

}

void getServerInfo(){

System.out.print("Server IP : ");     this.ip = this.scan.nextLine();

System.out.print("Server Port Number : ");   this.port = this.scan.nextInt();

this.scan.nextLine(); //enter key 날리자.

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

채팅

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Hashtable;


public class ChatServer {

private ServerSocket server;

private Socket client;

ChatServer(){   //constructor

try{

this.server = new ServerSocket(9999);

System.out.println("Chatting Server is ready...");

Hashtable<String, PrintWriter> ht = new Hashtable<String, PrintWriter>();

while(true){

this.client = this.server.accept();

ChatServerThread cst = new ChatServerThread(this.client, ht);

cst.start();

}

}catch(Exception ex){

ex.printStackTrace();

}

}

public static void main(String[] args) {

new ChatServer();

}

}






import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.Socket;

import java.util.Collection;

import java.util.Hashtable;

import java.util.Iterator;



public class ChatServerThread extends Thread {

private Socket client;

private Hashtable<String, PrintWriter> ht;

private String id;  //대화명

private BufferedReader br;

private PrintWriter pw;

public ChatServerThread(Socket client, Hashtable<String, PrintWriter> ht) {

this.client = client;

this.ht = ht;

try{

this.br = new BufferedReader(

new InputStreamReader(this.client.getInputStream()));

this.pw = new PrintWriter(

new BufferedWriter(new OutputStreamWriter(

this.client.getOutputStream())));

this.id = br.readLine();   //사용자의 아이디

synchronized(this.ht){

System.out.println("[" + this.id + "]님이 입장하셨습니다.");

this.ht.put(this.id, this.pw);

this.broadcast("[" + this.id + "]님이 입장하셨습니다.");

}

}catch(Exception ex){

ex.printStackTrace();

}

}

@Override

public void run(){

//Thread 가 해야할 일

try{

String line = null;

while((line = this.br.readLine()) != null){

if(line.equals("quit")) break;

this.broadcast("[" + this.id +"]" + line);

}

}catch(Exception ex){

ex.printStackTrace();

}finally{

synchronized(this.ht){

this.ht.remove(this.id);

}

this.broadcast("[" + this.id + "] 님이 퇴장하셨습니다.");

try{

if(this.br != null) this.br.close();

if(this.pw != null) this.pw.close();

if(this.client != null) this.client.close();

}catch(Exception ex){

ex.printStackTrace();

}

}

}

private void broadcast(String msg){

synchronized(this.ht){

Collection<PrintWriter> members = this.ht.values();

Iterator<PrintWriter> iters = members.iterator();

while(iters.hasNext()){

PrintWriter pw1 = iters.next();

pw1.println(msg);

pw1.flush();

}

}

}

}






import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.Socket;

import java.util.Scanner;



public class ChatClient {

private Socket client;

private String id;

private String ip;

private int port;

private Scanner scan;

private BufferedReader br;

private PrintWriter pw;

ChatClient(){

this.scan = new Scanner(System.in);

getServerInfo();

try{

this.client = new Socket(this.ip, this.port);

this.br = new BufferedReader(

new InputStreamReader(this.client.getInputStream()));

this.pw = new PrintWriter(

new BufferedWriter(new OutputStreamWriter(

this.client.getOutputStream())));

this.pw.println(this.id);  //서버에접속하면 가장먼저 아이디를 읽으므로, 클라이언트에서는 제일 먼저 아이디를 보내줘야 한다.

this.pw.flush();

ChatClientThread cct = new ChatClientThread(this.client, this.br); //서버로 부터 문자열을 받을 객체

cct.start();

}catch(Exception ex){

ex.printStackTrace();

}

}

private void getServerInfo(){

System.out.print("대화명 : ");     this.id = this.scan.nextLine();

System.out.print("서버IP : ");     this.ip = this.scan.nextLine();

System.out.print("서버 Port Number : ");  this.port = this.scan.nextInt();

this.scan.nextLine();   //마지막 엔터키 처리

}

private void service(){   //채팅서버로 문자열을 보내는 메소드

while(true){

System.out.print("[" + this.id + "] >> ");

String line = this.scan.nextLine();

if(line == null || line.equals("quit")){

this.pw.println("quit");  //서버에도 quit라고 보내고

this.pw.flush();

break;

}

this.pw.println(line);   this.pw.flush();

}

}

public static void main(String[] args) {

new ChatClient().service();

}

}







import java.awt.BorderLayout;

import java.awt.Container;

import java.io.BufferedReader;

import java.net.Socket;


import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;


public class ChatClientThread extends Thread {

private Socket client;

private BufferedReader br;

private JFrame f;

private JTextArea area;

private Container con;

private JScrollPane pane;

public ChatClientThread(Socket client, BufferedReader br) {

this.client = client;

this.br = br;

this.f = new JFrame("Chatting Window");

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.con = this.f.getContentPane();

this.con.setLayout(new BorderLayout());

this.area = new JTextArea();

this.pane = new JScrollPane(this.area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

               JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

this.con.add("Center", this.pane);

this.f.setSize(700, 400);

this.f.setVisible(true);

}

@Override

public void run(){    //서버가 보내준 문자열을 받는 메소드

try{

String line = null;

while((line = this.br.readLine()) != null){

this.area.append(line + "\n");

}

}catch(Exception ex){

ex.printStackTrace();

}finally{

try{

if(this.client != null) this.client.close();

}catch(Exception ex){

ex.printStackTrace();

}

}

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ


http://www.ubuntu.com/ 이동

Download-Desktop 이동. Ubuntu 13.10 64비트 버전 다운. 후 

VMware Workstation에 설치



File

import java.io.File;


public class FileDemo {

public static void main(String[] args) {

System.out.println("File.separator = " + File.separator);

System.out.println("file.separator = " + System.getProperty("file.separator"));

System.out.println("File.pathSeparator = " + File.pathSeparator);

System.out.println("path.separator = " + System.getProperty("path.separator"));

}

}

출력:

File.separator = /

file.separator = /

File.pathSeparator = :

path.separator = :

//윈도우즈는 파일구분이 \로, 리눅스는 /, 그리고 경로구분은 윈도우즈는 ; , 리눅스는 :

----------------------------------------------

import java.io.File;

import java.io.IOException;

import java.util.Scanner;


public class FileDemo1 {

public static void main(String[] args) {

FileDemo1 fd = new FileDemo1();

File file = new File(fd.getPath());

System.out.println("Path = " + file.getPath());

System.out.println("Absolute path = " + file.getAbsolutePath());

try{  //CanonicalPath는 익셉션을 던짐

System.out.println("Canonical path = " + file.getCanonicalPath());

}catch(IOException ex){}

}

String getPath(){

System.out.print("파일 경로 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

파일 경로 : src/FileDemo1.java

Path = src/FileDemo1.java

Absolute path = /home/mino/JavaRoom/0401/src/FileDemo1.java

Canonical path = /home/mino/JavaRoom/0401/src/FileDemo1.java

출력:

파일 경로 : ../0401/src/FileDemo1.java

Path = ../0401/src/FileDemo1.java

Absolute path = /home/mino/JavaRoom/0401/../0401/src/FileDemo1.java

Canonical path = /home/mino/JavaRoom/0401/src/FileDemo1.java

//getPath는 내가 입력한 경로. 진짜 절대경로는 CanonicalPath. AbsolutePath를 쓰는것이 일반적이지만 cannicalPath는 익셉션처리를 해주어야함.

//AbsolutePath를 두번째처럼 쓰는 경우는 거의 없기 때문에 일반적으로 AbsolutePath를 써도 괜찮다.

--------------------------------------------

import java.io.File;

import java.util.Date;

import java.util.Scanner;


public class FileDemo2 {

public static void main(String[] args) {

File file = new File(new FileDemo2().getPath());

if(file.exists()){

System.out.println("Name : " + file.getName());

System.out.println("Absolute : " + file.getAbsolutePath());

System.out.println("Permission : " + file.canRead());

System.out.println("Permission : " + file.canWrite());

System.out.println("Permission : " + file.canExecute());

System.out.println("file or directory : " + file.isDirectory());

System.out.println("Created Date : " + file.lastModified());

System.out.println("Created Date : " + new Date(file.lastModified()));

System.out.println("Size : " + file.length());

}else{

System.out.println("파일 혹은 디렉토리를 찾을 수 없습니다");

}

}

String getPath(){

System.out.print("파일 및 디렉토리 경로 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

파일 및 디렉토리 경로 : src/FileDemo2.java

Name : FileDemo2.java

Absolute : /home/mino/JavaRoom/0401/src/FileDemo2.java

Permission : true

Permission : true

Permission : false

file or directory : false

Created Date : 1396315823000

Created Date : Tue Apr 01 10:30:23 KST 2014

Size : 994

출력:

파일 및 디렉토리 경로 : /home/mino/JavaRoom

Name : JavaRoom

Absolute : /home/mino/JavaRoom

Permission : true

Permission : true

Permission : true

file or directory : true

Created Date : 1396313223000

Created Date : Tue Apr 01 09:47:03 KST 2014

Size : 4096

-----------------------------------------------------------

파일 이름변경

import java.io.File;

import java.util.Scanner;


public class FileDemo3 {

public static void main(String[] args) {

FileDemo3 fd = new FileDemo3();

File file = new File(fd.getPath());

if(file.exists()){

String newName = fd.getPath();

System.out.println(file.renameTo(new File(newName)));

}else System.out.println("Not Found");

}

String getPath(){

System.out.print("파일명 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

파일명 : /home/mino/sungjuk_utf8.dat

파일명 : /home/mino/sungjuk.dat

true

//처음에 이름을 변경할 파일을 입력하고, 두번째는 이름을 어떻게 바꿀건지 한다. 성공하면 true

-------------------------------------------------------

파일 삭제

import java.io.File;

import java.util.Scanner;


public class FileDemo3 {

public static void main(String[] args) {

FileDemo3 fd = new FileDemo3();

File file = new File(fd.getPath());

if(file.exists()){

System.out.println(file.delete());

}else System.out.println("Not Found");

}

String getPath(){

System.out.print("파일명 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

파일명 : /home/mino/sungjuk.dat

true

//파일이 삭제된다.

------------------------------------------------------------

목록

import java.io.File;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Scanner;


public class FileDemo4 {

public static void main(String[] args) {

File file = new File(new FileDemo4().getPath());

if(file.exists()){

if(file.isDirectory()){

File [] array = file.listFiles();  //디렉토리의 모든 파일을 파일 배열에 넣어줌.

for(File f : array){

System.out.print(f.getName() +"  \t\t");

String pattern = "MM월 dd   HH:mm";

SimpleDateFormat sdf = new SimpleDateFormat(pattern);

System.out.print(sdf.format(new Date(f.lastModified())) +"\t\t");

if(f.isDirectory()) System.out.println("<DIR>");

else System.out.println(f.length() + " Bytes");

}

}else System.out.println("디렉토리가 아닙니다.");

}else System.out.println("Not Found");

}

String getPath(){

System.out.print("디렉토리 경로 : ");

Scanner scan = new Scanner(System.in);

return scan.next();

}

}

출력:

디렉토리 경로 : src

FileDemo3.java   04월 01   10:40 508 Bytes

FileDemo1.java   04월 01   10:03 606 Bytes

FileDemo.java   04월 01   09:59 384 Bytes

FileDemo4.java   04월 01   10:54 970 Bytes

FileDemo2.java   04월 01   10:30 994 Bytes

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.Font;


import javax.swing.JFrame;

import javax.swing.JTree;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.DefaultTreeModel;


public class JTreeDemo {

private JFrame f;

private Container con;

private JTree tree;

private Font font;

private JTreeDemo(){

this.f = new JFrame("JTree Demo");

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.font = new Font("Monospaced", Font.PLAIN, 15);

this.con = this.f.getContentPane();

this.tree = new JTree();

}

private void display(){

this.con.setLayout(new BorderLayout());

this.tree.setFont(this.font);

this.tree.setModel(getModel());

this.con.add("Center", this.tree);

this.f.setSize(300, 800);

this.f.setLocationRelativeTo(null);

this.f.setVisible(true);

}

private DefaultTreeModel getModel(){

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java-Oracle");

DefaultMutableTreeNode os = new DefaultMutableTreeNode("OS");

DefaultMutableTreeNode windows = new DefaultMutableTreeNode("Windows8.1");

DefaultMutableTreeNode ubuntu = new DefaultMutableTreeNode("Ubuntu");

DefaultMutableTreeNode centos = new DefaultMutableTreeNode("CentOS");

os.add(windows);  os.add(ubuntu);  os.add(centos);

DefaultMutableTreeNode language = new DefaultMutableTreeNode("language");

DefaultMutableTreeNode c = new DefaultMutableTreeNode("C-language");

DefaultMutableTreeNode java = new DefaultMutableTreeNode("Java");

language.add(c);   language.add(java);

DefaultMutableTreeNode db = new DefaultMutableTreeNode("DB");

DefaultMutableTreeNode derby = new DefaultMutableTreeNode("Derby");

DefaultMutableTreeNode sqlite = new DefaultMutableTreeNode("Sqlite");

DefaultMutableTreeNode mysql = new DefaultMutableTreeNode("MySQL");

DefaultMutableTreeNode oracle = new DefaultMutableTreeNode("Oracle");

db.add(derby);  db.add(sqlite);  db.add(mysql);    db.add(oracle);

DefaultMutableTreeNode web = new DefaultMutableTreeNode("Web");

DefaultMutableTreeNode html5 = new DefaultMutableTreeNode("HTML5");

DefaultMutableTreeNode css3 = new DefaultMutableTreeNode("CSS3");

DefaultMutableTreeNode javascript = new DefaultMutableTreeNode("JavaScript");

DefaultMutableTreeNode ajax = new DefaultMutableTreeNode("Ajax");

DefaultMutableTreeNode xml = new DefaultMutableTreeNode("XML");

DefaultMutableTreeNode jquery = new DefaultMutableTreeNode("jQuery");

web.add(html5);  web.add(css3);   web.add(javascript);   web.add(ajax);

web.add(xml);   web.add(jquery);

DefaultMutableTreeNode framework = new DefaultMutableTreeNode("Framework");

DefaultMutableTreeNode struts = new DefaultMutableTreeNode("Struts");

DefaultMutableTreeNode spring = new DefaultMutableTreeNode("Spring");

framework.add(struts);  framework.add(spring);

DefaultMutableTreeNode project = new DefaultMutableTreeNode("Project");

DefaultMutableTreeNode first = new DefaultMutableTreeNode("1차 프로젝트");

DefaultMutableTreeNode second = new DefaultMutableTreeNode("2차 프로젝트");

DefaultMutableTreeNode third = new DefaultMutableTreeNode("3차 프로젝트");

project.add(first);  project.add(second);   project.add(third);

root.add(os);   root.add(language);   root.add(db);  root.add(web);

root.add(framework);   root.add(project);

DefaultTreeModel dtm = new DefaultTreeModel(root);

return dtm;

}

public static void main(String[] args) {

new JTreeDemo().display();

}

}

//출력은 "Java-Oracle"가 루트폴더, 그리고 아래 파일들이 정렬. 다같이 만들어줫으나 파일을 붙여주면 그것은 폴더처럼됨. 

펼치면 담겨있는 것을 볼 수 잇음.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

탐색기

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.Dimension;

import java.awt.Toolkit;


import javax.swing.JFrame;

import javax.swing.JSplitPane;

import javax.swing.JTable;

import javax.swing.JTextArea;

import javax.swing.UIManager;


public class Explorer {

private JFrame f;

private JSplitPane pane;

private Container con;

private LeftPane  left;

private JTable table;

private JTextArea ta;

private RightPane  right;

private Explorer(){

this.f = new JFrame("File Manager");

this.con = this.f.getContentPane();

this.pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);

this.right = new RightPane();

this.left = new LeftPane(this.right);

}

private void display(){

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.pane.setLeftComponent(this.left);

this.pane.setRightComponent(this.right);

this.con.setLayout(new BorderLayout());

this.con.add("Center", this.pane);

this.f.setLocationRelativeTo(null);

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

this.f.setSize((int)dim.getWidth(), (int)dim.getHeight());

this.f.setVisible(true);

}

public static void main(String[] args) {

//API에서 javax.swing.plaf.~~ 써져있는 것을 볼 수 있다.

//Metal : javax.swing.plaf.metal.MetalLookAndFeel

//GTK : com.su.java.swing.plat.gtk.GTKLookAndFeel    -안먹힘

//Nimbus : com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel

//Motif : com.sun.java.swing.plaf.motif.MotifLookAndFeel

//Windows : com.sun.java.swing.plaf.windows.WindowsLookAndFeel   -안먹힘

try{

UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

}catch(Exception ex){}

new Explorer().display();

}

}







import java.awt.CardLayout;


import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.JTextArea;


public class RightPane extends JPanel {

private JScrollPane scrollTable, scrollTextArea;

private JTable table;

private JTextArea ta;

private CardLayout card;

RightPane(){

this.card = new CardLayout();

this.setLayout(card);

this.table = new JTable();

this.scrollTable = new JScrollPane(this.table);    //디렉토리를 선택했을 때

this.ta = new JTextArea();

this.scrollTextArea = new JScrollPane(this.ta);   //파일을 선택했을 때

this.add(this.scrollTable, "table");

this.add(this.scrollTextArea, "area");

card.show(this, "table");

this.setSize(480, 700);

}

JTable getTable(){ return this.table; }

void setTable(JTable table){ this.table = table; }

JTextArea getTextArea() { return this.ta; }

void setTextArea(JTextArea ta) { this.ta = ta; }

CardLayout getCardLayout(){  return this.card; }

}








import java.awt.BorderLayout;

import java.awt.Dimension;

import java.io.File;


import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTree;

import javax.swing.tree.DefaultMutableTreeNode;


LeftPane(RightPane right){

//Linux, Unix

this.right = right;

this.root = new DefaultMutableTreeNode("내 컴퓨터");

//루트 디렉토리(드라이브명)을 출력

File [] array = File.listRoots();  //모든 루트 디렉토리를 돌려준다.

for(File f : array){

if(f.isDirectory()){  //디렉토리라면

DefaultMutableTreeNode node = new DefaultMutableTreeNode(f.getPath());

node.add(new DefaultMutableTreeNode("EMPTY"));  //각폴더에 모두 empty를 넣음. 모두 폴더화. 확장은 이벤트에 의해 해주기 위해.

this.root.add(node);

}

}

//특정 루트 디렉토리의 디렉토리만을 출력(특정 드라이브)

/*File file = new File("c:/");  

File [] array = file.listFiles();  //루트밑에있는 폴더들을 모두 파일 배열에 넣음.

for(File f : array){

if(f.isDirectory()){  //디렉토리라면

DefaultMutableTreeNode node = new DefaultMutableTreeNode(f.getName());

node.add(new DefaultMutableTreeNode("EMPTY"));  //각폴더에 모두 empty를 넣음. 모두 폴더화. 확장은 이벤트에 의해 해주기 위해.

this.root.add(node);

}

}*/

//루트디렉토리 출력을 toString을 사용하는 방법

/* File [] array = File.listRoots();    // 변경 : Root부터 디렉토리(C:\, D:\, ...)를 찾음

   for(int i = 0; i< array.length; i++){

       if(array[i].isDirectory()){  // 변경 

          DefaultMutableTreeNode node = new DefaultMutableTreeNode(array[i].toString().trim()); // 변경 : Root밑에 디렉토리(C:\, D:\, ...)를 연결함

          node.add(new DefaultMutableTreeNode("EMPTY"));

          this.root.add(node);

       }


   }*/


this.tree = new JTree(this.root);

this.tree.addTreeWillExpandListener(new TreeAction());  //트리확장할 것이다.

this.tree.addTreeSelectionListener(new TreeSelection(this, this.right));

this.scroll = new JScrollPane(this.tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

                                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

this.setLayout(new BorderLayout());

this.add("Center", this.scroll);

this.setPreferredSize(new Dimension(200,  700));

}

}







import java.io.File;

import java.util.Enumeration;

import java.util.StringTokenizer;


import javax.swing.event.TreeExpansionEvent;

import javax.swing.event.TreeWillExpandListener;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.ExpandVetoException;

import javax.swing.tree.MutableTreeNode;

import javax.swing.tree.TreeNode;

import javax.swing.tree.TreePath;


public class TreeAction implements TreeWillExpandListener {


@Override

public void treeWillExpand(TreeExpansionEvent event)

throws ExpandVetoException {

TreePath path = event.getPath();

//System.out.println(path);    출력 -> [/, home]

StringTokenizer st = new StringTokenizer(path.toString(), "[,]");

st.nextToken();   //   /를 날려주고 뒤에 폴더이름만 가져오게 하기 위해

//System.out.println(st.nextToken());  출력 -> usr, home ~~~~

if(st.hasMoreTokens()){  //다음토큰이 있는 경우에 오류발생 방지.

String node = File.separator + st.nextToken().trim();    //     /home

//System.out.println(node);  //출력-> /tmp, /home, ~~

while(st.hasMoreTokens()){  //[1,home,계정]이니 다음이 없을 때까지

node += File.separator + st.nextToken().trim();

}

File file = new File(node); /////            /home

//System.out.println(file.getAbsolutePath());  //절대경로를 출력

File [] array = file.listFiles();

if(array == null) return;  //자식이 없으면 그냥 넘기고

DefaultMutableTreeNode temp =    //home

 (DefaultMutableTreeNode)event.getPath().getLastPathComponent();

temp.removeAllChildren();  //붙이기전에 다지움. 이걸 하지 않으면 자기자신을 택하면 또 자기자신이 나오는 현상 발생

for(File f : array){

if(f.isDirectory()){

DefaultMutableTreeNode tn = new DefaultMutableTreeNode(f.getName());

tn.add(new DefaultMutableTreeNode("EMPTY"));  //마지막 폴더를 선택했을 때 비어있다면 empty표시

temp.add(tn);

}else if(f.isFile()){

temp.add(new DefaultMutableTreeNode(f.getName()));

}

}

}

}


@Override

public void treeWillCollapse(TreeExpansionEvent event)

throws ExpandVetoException {}

}






import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Vector;


import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.event.TreeSelectionEvent;

import javax.swing.event.TreeSelectionListener;

import javax.swing.table.DefaultTableModel;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.TreeNode;

import javax.swing.tree.TreePath;


public class TreeSelection implements TreeSelectionListener {

private JPanel panel;

private RightPane right;

TreeSelection(JPanel panel, RightPane right){

this.panel = panel;

this.right = right;

}

@Override

public void valueChanged(TreeSelectionEvent e) {

TreePath path = e.getPath();

//System.out.println(path);    //[/, home]

DefaultMutableTreeNode node = 

(DefaultMutableTreeNode)e.getPath().getLastPathComponent();  //경로상의 제일 마지막 

//System.out.println(node);  // home, sys 처럼 앞의 경로는 두고 마지막 경로상의 값만 출력한다.

TreeNode [] array = node.getPath();

String str = "";

for(int i = 1 ; i < array.length ; i++){  //1부터 쓴 이유는 출력이 usr을 찎으면 ///usr로 시작한다. 처음에 /로 시작하고 separator붙여주고 해서 제일처음 부분을 제거한 것이다.

str += File.separator + array[i];

}

File file = new File(str);

if(file.isDirectory()){  //디렉토리를 선택했다면

File [] fileArray = file.listFiles();

Vector<String> columnVector = new Vector<String>(1,1);

columnVector.addElement("Name");

columnVector.addElement("Modifeied Date");

columnVector.addElement("Directory");

columnVector.addElement("size");

Vector<Object> dataVector = new Vector<Object>(1,1);

for(File f : fileArray){

Vector<String> imsi = new Vector<String>(1,1);

imsi.addElement(f.getName());

long date = f.lastModified();

String pattern = "YYYY-MM-dd HH:mm:ss";

SimpleDateFormat sdf = new SimpleDateFormat(pattern);

imsi.addElement(sdf.format(new Date(date)));

if(f.isDirectory()) imsi.addElement("<DIR>");

else if (f.isFile()) imsi.addElement("");

imsi.addElement(f.length() + "Bytes");

dataVector.addElement(imsi);

}

DefaultTableModel model = new DefaultTableModel(dataVector, columnVector);

this.right.getTable().setModel(model);

this.right.getCardLayout().show(this.right,"table");

}else if(file.isFile()){

BufferedReader br = null;

String line = "", line1 = "";

try{

br = new BufferedReader(new FileReader(file));

while((line = br.readLine()) != null){

line1 += line + "\n";

}

this.right.getTextArea().setText("");  //텍스트공간 초기화

this.right.getTextArea().append(line1);

this.right.getCardLayout().show(right, "area");

}catch (IOException e2){

JOptionPane.showMessageDialog(this.panel, e2.getMessage());

}finally{

try{

if(br != null) br.close();

}catch(IOException ex){}

}

}

}

}

----------------------------------------------------------

(참조)

1) 루트 디렉토리명만 출력하기(드라이브명)

File file[];

file = File.listRoots();

for(i =0 ; i<file.length ; i++)

{

    System.out.println(file[i].toString());

}

2) 특정 루트 디렉토리의 디렉토리만을 출력(특정 드라이브)

import java.io.*;

class rootDirectoryList

{

    public void list()

    {

        File root=new File("c:/");

        File file[]=root.listFiles();

        

        int i;

        for(i=0 ; i<file.length ; i++)

        {

            if(file[i].isDirectory())

            {

                System.out.println(file[i].toString());

            }

        }

        

    }

    

    public static void main(String args[])

    {

        rootDirectoryList l=new rootDirectoryList();

        l.list();

    }

}


출처:

http://cafe.naver.com/04itschool/299

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

직렬화

java.io.Serializable 의 자식은 직렬화가 가능.(오버라이드할 것이 하나도 없음)

preemitive 타입은 직렬화가 가능.

String, Vector, Date 는 Serializable 의 자식이므로 직렬화 가능.


import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

import java.util.Date;


public class SerializationDemo {

public static void main(String[] args) {

Date date = new Date();

System.out.println(date.toString());  //Tue Apr 01 16:05:46 KST 2014

ObjectOutputStream oos = null;

try{

String path = "/home/mino/Temp";

oos = new ObjectOutputStream(

new FileOutputStream(new File(path, "date.ser")));

oos.writeObject(date);

System.out.println("잘 저장됐습니다.");

}catch(IOException ex){

}finally{

try{

oos.close();

}catch(IOException ex){}

}

}

}

//만들어진 파일을 열면 제대로된 글자가 안나온다. 하지만 역직렬화를 통해 다시 불러오면 제대로보인다.

--------------------------------

역직렬화  - 직렬화한 것을 복원

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.util.Date;



public class SerializationDemo1 {

public static void main(String[] args) {

String path = "/home/mino/Temp";

ObjectInputStream ois = null;

try {

ois = new ObjectInputStream(new FileInputStream(new File(path, "date.ser")));

Object obj = ois.readObject();

if(obj instanceof Date){

Date before = (Date)obj;

System.out.println(before);

}

} catch (Exception e) {

} finally{

try {

if(ois != null) ois.close();

} catch (Exception e2) {}

}

}

}

출력:

Tue Apr 01 16:06:51 KST 2014

-------------------------------------------------------------

직렬화


public class Student implements java.io.Serializable { //이것을 implements 하지않으면 Student는 serializable하지 않기에 에러발생.

private String hakbun, name;

private int kor, eng, mat, edp;

public Student(String hakbun, String name, int kor, int eng, int mat,

int edp) {

super();

this.hakbun = hakbun;

this.name = name;

this.kor = kor;

this.eng = eng;

this.mat = mat;

this.edp = edp;

}

@Override

public String toString(){

return String.format("%-10s%10s%5d%5d%5d%5d",

             this.hakbun, this.name, this.kor, this.eng, this.mat, this.edp);

}

public String getHakbun() {

return hakbun;

}

public void setHakbun(String hakbun) {

this.hakbun = hakbun;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getKor() {

return kor;

}

public void setKor(int kor) {

this.kor = kor;

}

public int getEng() {

return eng;

}

public void setEng(int eng) {

this.eng = eng;

}

public int getMat() {

return mat;

}

public void setMat(int mat) {

this.mat = mat;

}

public int getEdp() {

return edp;

}

public void setEdp(int edp) {

this.edp = edp;

}

}






import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.util.Vector;


public class Input {

private Vector<Student> vector;


Input(Vector<Student> vector) {

this.vector = vector;

}

void input(){

BufferedReader br = null;

String line = null;

try{

String path = "/home/mino/Downloads/sungjuk_utf8.dat";

br = new BufferedReader(new FileReader(new File(path)));

while((line = br.readLine()) != null){

String [] array = line.split("\\s+");

Student s = new Student(array[0], array[1], Integer.parseInt(array[2]),

              Integer.parseInt(array[3]), Integer.parseInt(array[4]),

              Integer.parseInt(array[5]));

this.vector.addElement(s);

}

}catch(IOException ex){

}finally{

try{

if(br != null) br.close();

}catch(IOException ex){}

}

}

}






import java.io.File;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;

import java.util.Vector;



public class SerializationDemo2 {

public static void main(String[] args) throws Exception{

Vector<Student> vector = new Vector<Student>(1,1);

Input input = new Input(vector);

input.input();

String path = "/home/mino/Temp";

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(path, "student.ser")));

//객체의 직렬화는 reader와 writer를 쓰지않는다. byte를 쓰는 OutputStream을 사용한다.

oos.writeObject(vector);

System.out.println("Success");

oos.close();

}

}

-------------------------------

역직렬화

import java.io.File;

import java.io.FileInputStream;

import java.io.ObjectInputStream;

import java.util.Vector;



public class SerializationDemo3 {

public static void main(String[] args) throws Exception{

String path = "/home/mino/Temp";

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(path, "student.ser")));

Object obj = null;

obj = ois.readObject();

Vector<Student> vector = (Vector<Student>)obj;

//System.out.println(vector.size());

for(Student s : vector){

System.out.println(s);

}

ois.close();

}

}

출력:

1101             한송이   78   87   83   78

1102             정다워   88   83   57   98

1103             그리운   76   56   87   78

1104             고아라   83   57   88   73

1105             사랑해   87   87   53   55

1106             튼튼이   98   97   93   88

1107             한아름   68   67   83   89

1108             더크게   98   67   93   78

1109             더높이   88   99   53   88

1110             아리랑   68   79   63   66

1111             한산섬   98   89   73   78

1112             하나로   89   97   78   88

----------------------

만약 위에서 Student Class에서 

transient private String name; //transient를 쓰면 이것을 빼고 직렬화를 하겠다.

위와 같이 쓰면 아래와 같이 출력된다. 출력전에는 한번더 직렬화를 해주고 역직렬화를 실행해야 한다.

1101            null   78   87   83   78

1102            null   88   83   57   98

1103            null   76   56   87   78

1104            null   83   57   88   73

1105            null   87   87   53   55

1106            null   98   97   93   88

1107            null   68   67   83   89

1108            null   98   67   93   78

1109            null   88   99   53   88

1110            null   68   79   63   66

1111            null   98   89   73   78

1112            null   89   97   78   88


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

=======================================================================

java.net

1. OSI7 Layers - ISO

Application Layer

Presentation Layer

Session Layer

Transport Layer -> TCP, UDP

Network Layer --> IP

Datalink Layer --> MAC Address(물리적주소)

Phisical Layer


802Model - IEEE



2. TCP, UDP

TCP --> Connection Oriented Protocol  //확실히 전송되어 안정성이 필요한 곳에서 사용. 느림.

UDP --> Connection-less Protocol   //안정성보다 속도가 빨라야하는 곳에서 사용.


3. Socket

1)IP --> DNS(를통해 IP를 알아냄)

2)#Port

 - 0 ~ 1023 : Well-known Port Number.

 - 1024 ~ 2048 :Vendor Port.

 - 2049 ~ 65535 : User Port.



Inet Address

URL

URLConnection

URLEncode

URLDecode


ServerSocket

Socket


DatagramPacket

DatagramSocket

------------------------------------------

InetAddress

import java.net.InetAddress;

import java.net.UnknownHostException;

import java.util.Scanner;



public class InetAddressDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("Hostname : ");

String hostname = scan.next();

InetAddress ia = null;

try{

ia = InetAddress.getByName(hostname); //생성자가없어서 new 못씀  //단점: 하나만 읽어온다.

System.out.printf("%s --> %s\n", ia.getHostName(), ia.getHostAddress());

}catch(UnknownHostException ex){

System.out.println(ex.getMessage());

}

}

}

출력:

Hostname : www.naver.com

www.naver.com --> 202.131.30.11

출력:

Hostname : www.google.com

www.google.com --> 173.194.38.83

----------------------------------

쓰는 아이피 전체를 읽음.

import java.net.InetAddress;

import java.net.UnknownHostException;

import java.util.Scanner;


public class InetAddressDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("Hostname : ");

String hostname = scan.next();

InetAddress [] array = null;

try{

array = InetAddress.getAllByName(hostname);

for(InetAddress ia : array)

System.out.printf("%s --> %s\n", ia.getHostName(), ia.getHostAddress());

}catch(UnknownHostException ex){

System.out.println(ex.getMessage());

}

}

}

출력:

Hostname : www.naver.com

www.naver.com --> 202.131.30.12

www.naver.com --> 125.209.222.141

출력:

Hostname : www.google.com

www.google.com --> 173.194.117.243

www.google.com --> 173.194.117.242

www.google.com --> 173.194.117.240

www.google.com --> 173.194.117.244

www.google.com --> 173.194.117.241

www.google.com --> 2404:6800:4004:807:0:0:0:1013

----------------------------------------------------

자기 컴퓨터의 호스트이름과 아이피를 출력하는 소스

import java.net.InetAddress;

import java.net.UnknownHostException;


public class InetAddressDemo1 {

public static void main(String[] args) throws UnknownHostException{

InetAddress ia = null;

ia = InetAddress.getLocalHost();

System.out.println(ia.getHostName() + "  --> " + ia.getHostAddress());

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

====================================================================

VMware Workstation 깔아서 윈도우 깔기.

http://www.vmware.com/ 이동. 다운로드 탭에서 VMware Workstation 눌러줌.

VMware Workstation 10 for Linux 32-bit 다운로드.

다운받은 파일은 실행파일이 아니기 때문에 터미널에서 chmod +x VMware*.i386.bundle로 실행되게 해줌.

그리고 sudo apt-get update 로 캐시 업데이트 후.

sudo apt-get install build-essential linux-headers-$(uname -r) 해서 설치.

gksudo bash ./VMware*.i386.bundle 로 설치하는데, next 누르다가 시작시업데이트 Yes 누르고 다음은 NO 한번 눌러주고  계속 next

체험판을 쓸것이기때문에 시리얼넘버는 안넣어줌.

그리고 윈도우 설치.


vmware workstation으로 윈도우 부팅시 한글 적용.

/etc/vmware 의 config 파일을 sudo gedit config 로 열어서 제일 아랫줄에 추가

xkeymap.keysym.Hangul = 0x0f2

xkeymap.keysym.Hangul_Hanja = 0x0f1


우분투 한글

터미널에서 sudo gedit ~/.Xmodmap 열어서

keycode 122 = Hangul

keycode 121 = Hangul_Hanja

추가 후 재부팅. (파일이 없으면 그냥 열어줌)

I/O

Byte Vs Character 어떤것으로 읽을것이냐

Stream Vs RandomAccess 어떻게 읽을것이냐

data Vs metadata 핸들링은 어떻게


Stream 두가지 특징.

1. Sequence : 데이터가 순서대로 들어옴.

2. Concurency X : 동시성을 가지지 않는다. 읽어오면 읽어오기만 할 수 있고 그외는 실행하지않는다.


byte는 InputStream and OutputStream로 처리

character는 Reader and Writer 로 처리

-----------------------------------------

byte

import java.io.IOException;

import java.io.InputStream;


public class InputDemo {

public static void main(String[] args) {

System.out.println("한개의 글자를 입력하세요 : ");

InputStream is = System.in;

int su = 0;

try{

su = is.read();  //하나를 읽어서 su에 넣어줌.

System.out.println("su = " + su);

}catch(IOException ex){}

}

}

출력:

한개의 글자를 입력하세요 : 

a

su = 97

//아스키코드 값로 받는다.

System.out.println("su = " + (char)su); 

//위와 같이 쓰면 한개의 글자를 입력 받으면, 입력받은 글자를 출력한다.

------------

import java.io.IOException;

import java.io.InputStream;


public class InputDemo {

public static void main(String[] args) {

System.out.println("좋아하는 계절 입력하세요 : ");

InputStream is = System.in;

int su = 0;

String str = "";

try{

while(true){

su = is.read();

if(su<0 || (char)su == '\n') break;

str += (char)su;

}

System.out.println("str = " + str);

}catch(IOException ex){}

}

}

출력:

좋아하는 계절 입력하세요 : 

spring

str = spring

//위의 두개의 코드는 한글을 입력받지 못한다. 입력하면 깨지는 현상이 발생하거나 전혀다른값을 얻는다.

--------------------------------------

import java.io.IOException;

import java.io.InputStream;


public class InputDemo1 {

public static void main(String[] args) {

System.out.print("좋아하시는 계절을 입력하세요 : ");

InputStream is = System.in;

int count = 0;

byte [] buffer = new byte[10];

String str = "";

try{

while((count = is.read(buffer)) >= 0){

str += new String(buffer, 0, count);  //(byte[] bytes, 얼마부터, 몇개)

}

System.out.println("str = " + str);

}catch(IOException ex){

System.out.println(ex.getMessage());

}

}

}

//한글입력이 가능한 코드. 그런데 잘 안나오넹... 

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

파일처리

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Scanner;


public class FileInputDemo {

public static void main(String[] args) {

FileInputDemo fid = new FileInputDemo();

String path = fid.getPath();

byte [] buffer = new byte[512];

int count = 0;

FileInputStream fis = null;

String str = "";

try{

fis = new FileInputStream(path);   //open

while ((count = fis.read(buffer)) > 0 ){

str += new String(buffer, 0, count);

}

System.out.println(str);

}catch(FileNotFoundException ex){

System.out.println("File Not Found");

}catch(IOException ex){

System.out.println((ex.getMessage()));

}finally{

try{  //파일을 닫을때도 exception 처리를 해줘야함.

fis.close();                                  //close

}catch(IOException ex){}

}

}

String getPath(){

Scanner scan = new Scanner(System.in);

System.out.print("읽고 싶은 파일 경로 : ");

return scan.next();

}

}

출력:

읽고 싶은 파일 경로 : /home/mino/sungjuk_utf8.dat

1101     한송이     78     87     83    78

1102     정다워     88     83     57    98

1103     그리운     76     56     87    78

1104     고아라     83     57     88    73

1105     사랑해     87     87     53    55

1106     튼튼이     98     97     93    88

1107     한아름     68     67     83    89

1108     더크게     98     67     93    78

1109     더높이     88     99     53    88

1110     아리랑     68     79     63    66

1111     한산섬     98     89     73    78

1112     하나로     89     97     78    88

----------------------------------------------------------

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Scanner;


public class FileInputDemo {

public static void main(String[] args) {

FileInputDemo fid = new FileInputDemo();

String path = fid.getPath();

//byte [] buffer = new byte[512];

int su = 0;

FileInputStream fis = null;

//String str = "";

try{

fis = new FileInputStream(path);   //open

while(true) {

su = fis.read();

if(su < 0) break;

System.out.print((char)su);

}

}catch(FileNotFoundException ex){

System.out.println("File Not Found");

}catch(IOException ex){

System.out.println(ex.getMessage());

}finally{

try{

fis.close();                                  //close

}catch(IOException ex){}

}

}

String getPath(){

Scanner scan = new Scanner(System.in);

System.out.print("읽고 싶은 파일 경로 : ");

return scan.next();

}

}

출력:

읽고 싶은 파일 경로 : src/FileInputDemo.java

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Scanner;


public class FileInputDemo {

~~~~~이어짐

------------------------위코드를 A~Z, a~z의 개수를 세는 프로그램

//영어 알파벳 카운트

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Scanner;


public class FileInputDemo1 {

public static void main(String[] args) {

FileInputDemo1 fid = new FileInputDemo1();

String path = fid.getPath();

int [] array = new int[52];

int su = 0;

FileInputStream fis = null;

try{

fis = new FileInputStream(path);   //open

while(true) {

su = fis.read();

if(su < 0) break;

if(su >= 65 && su <= 90){   //알파벳 대문자일 경우   

++array[su - 65];

}else if(su >= 97 && su <= 122){  //알파벳 소문자일 경우

++array[su - 71];

}

}

fid.output(array);

}catch(FileNotFoundException ex){

System.out.println("File Not Found");

}catch(IOException ex){

System.out.println(ex.getMessage());

}finally{

try{

fis.close();                                  //close

}catch(IOException ex){}

}

}

void output(int [] array){

int count = 0;

for(int i = 0 ; i < 26 ; i++){

System.out.printf("%c = %d\t", (i +65), array[i]);

count++;

if(count % 5 == 0) System.out.println();

}

System.out.println();

count = 0;

for(int i = 26 ; i < array.length ; i++){

System.out.printf("%c = %d\t", (i +71), array[i]);

count++;

if(count % 5 == 0) System.out.println();

}

}

String getPath(){

Scanner scan = new Scanner(System.in);

System.out.print("읽고 싶은 파일 경로 : ");

return scan.next();

}

}

출력:

읽고 싶은 파일 경로 : src/FileInputDemo.java

A = 0 B = 0 C = 0 D = 3 E = 5

F = 12 G = 0 H = 0 I = 9 J = 0

K = 0 L = 0 M = 1 N = 3 O = 3

P = 2 Q = 0 R = 0 S = 15 T = 0

U = 0 V = 0 W = 0 X = 0 Y = 0

Z = 0

a = 32 b = 6 c = 23 d = 7 e = 53

f = 10 g = 9 h = 9 i = 46 j = 4

k = 1 l = 22 m = 16 n = 44 o = 29

p = 24 q = 0 r = 29 s = 24 t = 60

u = 24 v = 5 w = 5 x = 10 y = 10

z = 0

---------------------------------------------------------

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;


//java BufferedDemo  원본  타겟

public class BufferedDemo {

public static void main(String[] args) {

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

if(args.length != 2){  //두개가 들어와야하는데 파라미터가 두개가아니면

System.out.println("잘못된 명령어입니다.");

System.out.println("Usage : java BufferedDemo  source  target");

System.exit(-1);

}

int su = 0, count = 0;

try {

bis = new BufferedInputStream(new FileInputStream(new File(args[0].trim())));

bos = new BufferedOutputStream(new FileOutputStream(new File(args[1].trim())));

while(bis.read()>=0){ 

bos.write(su);  //하나읽고 하나보내주는 방식

count++;

}

System.out.printf("%d bytes copy successfully.", count);

} catch (IOException e) {

System.out.println(e.getMessage());

} finally{

try{

if(bis != null) bis.close();

if(bos != null) bos.close();

}catch (IOException e) {}

}

}

}

//출력은 터미널창에가서 아래와 같이 쓰면

mino@Ubuntu-22:~/JavaRoom/0331/bin$ java BufferedDemo ../src/BufferedDemo.java /home/mino/Downloads/test.java

1161 bytes copy successfully.mino@Ubuntu-22:~/JavaRoom/0331/bin$ ^C

실행을 하고 그뒤에 복사할내용 그리고 저장될위치를 적어주면, 저장된위치를 가보면 test.java파일이 생성되어있다. 그 내용은 BufferedDemo.java의 내용과 같다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

스트림을 리더로, 바이트를 캐릭터로 바꿔주는

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;


//Bridge Class : InputStream --> Reader

public class InputStreamReaderDemo {

public static void main(String[] args) throws IOException{  //위에서는 try,catch를 썼지만 익숙해졌으니 편하게 던지자.

System.out.print("당신은 어느 계절을 좋아하시나요 ? ");

//InputStream is = System.in;   //byte

BufferedReader br = null;

br = new BufferedReader(new InputStreamReader(System.in));  //위위주석라인을 여기에 합친 것임.

String season = br.readLine(); //BufferedReader로 입력받으면 한줄을 입력받는 명령어가 있다.

System.out.println("season = "  + season);

br.close();

}

}

출력:

당신은 어느 계절을 좋아하시나요 ? 가을

season = 가을

--------------------------------------------------------

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;


//char --> byte : Writer --> OutputStream

public class OutputStreamWriterDemo {

public static void main(String[] args) throws IOException{

int su = 5;

double avg = 89.5;

String name = "한송이";

char grade = 'B';

boolean isStop = true;

OutputStreamWriter osw = null;

osw = new OutputStreamWriter(new FileOutputStream(new File("./result.dat")));

osw.write(name + " : " + avg + "," + isStop + "," + grade);

osw.close();

}

}

출력은 프로젝트를 refresh하면 생김.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;



public class PrintWriterDemo {

public static void main(String[] args) throws IOException {

String line = "1101     한송이     78     87     83    78";

//PrintStream ps = null;

//BufferedWriter bw = null;

PrintWriter pw = null;  //

pw = new PrintWriter(new BufferedWriter(new FileWriter(new File("./result.txt"))));

pw.println(line);

pw.flush();  //buffer를하면 항상 flush를 써줘야함.

pw.close();

}

}

출력은 프로젝트를 refresh하면 생김.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

NotePad 만들기

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.Font;

import java.awt.GraphicsEnvironment;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.InputEvent;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Vector;


import javax.swing.DefaultComboBoxModel;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JToolBar;

import javax.swing.KeyStroke;

import javax.swing.filechooser.FileNameExtensionFilter;



public class Notepad extends KeyAdapter implements ActionListener, ItemListener{

private JFrame f;

private Container con;

private JToolBar toolbar;

private JButton btnNew, btnOpen, btnSave;

private JScrollPane pane;

private JTextArea ta;

private int count;

private JComboBox<String> combo, combo1 ;

private Font font;

private JMenuBar mb;

private JMenu mFile, mHelp;

private JMenuItem miOpen, miSave, miNew, miExit;

private Notepad(){

this.f = new JFrame("Notepad");

this.con = this.f.getContentPane();

miNew = new JMenuItem("New", new ImageIcon("images/new.gif"));  //메뉴아이템에서 글씨와 그림을 둘다 넣음.

miNew.setMnemonic(KeyEvent.VK_N);  //단축키를 n으로 줌.

miNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, 

       InputEvent.CTRL_MASK)); //단축키를 n으로주고 ctrl + n 으로 누르면 실행되게

miNew.addActionListener(this);

mFile = new JMenu("File");  

miOpen = new JMenuItem("Open");  //메뉴아이템에서 글씨만 주는경우

miOpen.setMnemonic(KeyEvent.VK_O);

miOpen.addActionListener(this);

miSave = new JMenuItem(new ImageIcon("images/save.gif"));  //메뉴아이템에서 그림만 주는경우. 그림에는 단축키 불가능.

mFile = new JMenu("File");

miOpen = new JMenuItem("Open");

miOpen.setMnemonic(KeyEvent.VK_O);

miOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, 

InputEvent.CTRL_MASK));

miOpen.addActionListener(this);

miSave = new JMenuItem(new ImageIcon("images/save.gif"));

miSave.addActionListener(this);

miExit = new JMenuItem("Exit", KeyEvent.VK_X);

miExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, 

InputEvent.CTRL_MASK));

miExit.addKeyListener(this);

miExit.addActionListener(this);

mFile.add(miNew);

mFile.add(miOpen);

mFile.add(miSave);

mFile.addSeparator();

mFile.add(miExit);

mHelp = new JMenu("Help");

this.mb = new JMenuBar();

this.mb.add(mFile);

this.mb.add(mHelp);

//this.mb.setHelpMenu(mHelp);

this.f.getRootPane().setJMenuBar(mb);

this.font = new Font("Monospaced", Font.PLAIN, 10);

this.toolbar = new JToolBar();

this.btnNew = new JButton(new ImageIcon("images/new.gif"));

this.btnNew.addActionListener(this);

this.btnOpen = new JButton(new ImageIcon("images/open.gif"));

this.btnOpen.addActionListener(this);

this.btnSave = new JButton(new ImageIcon("images/save.gif"));

this.btnSave.addActionListener(this);

this.ta = new JTextArea();

this.ta.setFont(font);

this.pane = new JScrollPane(this.ta, 

                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 

                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

String [] array = {"2","5","8","10","12","14","18","20","25","30","35","40"};

this.combo = new JComboBox<String>(array);

this.combo.addItemListener(this);

this.combo1 = new JComboBox<String>();

this.combo1.addItemListener(this);

}

private void display(){

f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

this.f.addWindowListener(new WindowAdapter(){

@Override

public void windowClosing(WindowEvent evt){

exitComm();

}

});

this.con.setLayout(new BorderLayout());

this.toolbar.add(this.btnNew);

this.toolbar.add(this.btnOpen);

this.toolbar.addSeparator();

this.toolbar.add(this.btnSave);

this.toolbar.addSeparator();

this.toolbar.add(this.combo);

this.combo.setSelectedItem(new String("10"));  //처음 기본으로 선택되어있는 사이즈가10

this.combo1.setModel(getModel());

this.combo1.setSelectedItem(new String("Monospaced")); //처음 기본으로 선택된폰트

this.toolbar.add(this.combo1);

this.con.add("North", this.toolbar);

this.con.add("Center", this.pane);

f.setSize(600,500);

f.setLocationRelativeTo(null);

f.setVisible(true);

}

private DefaultComboBoxModel getModel(){

Vector<String> vector = new Vector<String>(1,1);

GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

String [] fontArray = env.getAvailableFontFamilyNames();

for(String str : fontArray)  vector.addElement(str);

return new DefaultComboBoxModel(vector);

}

@Override

public void keyReleased(KeyEvent evt){

switch(evt.getKeyCode()){

case KeyEvent.VK_X : exitComm(); break;

//case 'o' :

case KeyEvent.VK_S : saveFile();  break;

}

}

@Override

public void itemStateChanged(ItemEvent evt){

String str = (String)this.combo.getSelectedItem();

String fontname  = (String)this.combo1.getSelectedItem();

this.ta.setFont(new Font(fontname, Font.PLAIN, Integer.parseInt(str)));

}

@Override

public void actionPerformed(ActionEvent evt){

if(evt.getSource() == btnNew || evt.getSource() == miNew){

this.f.setTitle("Noname" + ++count +" - Notepad");

this.ta.setText("");

}else if(evt.getSource() == btnOpen || evt.getSource() == miOpen){

JFileChooser jc = new JFileChooser(".");

FileNameExtensionFilter filter = new FileNameExtensionFilter(

       "TXT & DAT Files", "txt", "dat");

jc.setFileFilter(filter);

int choice = jc.showOpenDialog(this.f);

if(choice == JFileChooser.APPROVE_OPTION){

File file = jc.getSelectedFile();

openFile(file);

}else return;

}else if(evt.getSource() == btnSave || evt.getSource() == miSave){

saveFile();

}else if(evt.getSource() == miExit){

exitComm();

}

}

private void exitComm(){  //종료버튼을 눌렀을때

if(ta.getText().length() > 0){ //한글자라도 입력되어있다면

int choice = JOptionPane.showConfirmDialog(f, "저장하시겠습니까?", 

                                     "종료", JOptionPane.YES_NO_CANCEL_OPTION,

                                     JOptionPane.QUESTION_MESSAGE);

switch(choice){

case JOptionPane.YES_OPTION : saveFile(); break;

case JOptionPane.NO_OPTION : System.exit(0); break;

case JOptionPane.CANCEL_OPTION :  break;

}

}else System.exit(0);  //한글자도 입력이 안되어있으면 그냥 종료

}

private void saveFile(){

JFileChooser jc = new JFileChooser(".");

FileNameExtensionFilter filter = new FileNameExtensionFilter(

       "TXT || DAT || Java Files", "txt", "dat", "java");

jc.setFileFilter(filter);

int choice = jc.showSaveDialog(this.f);

File file = null;

if(choice == JFileChooser.APPROVE_OPTION) 

file = jc.getSelectedFile();

else return;

BufferedWriter bw = null;

try {

bw = new BufferedWriter(new FileWriter(file));

bw.write(this.ta.getText());

this.f.setTitle(file.getAbsolutePath() + " - Notepad");

} catch (IOException e) {

JOptionPane.showMessageDialog(this.f, e.getMessage());

} finally{

try {

bw.close();

} catch (IOException e2) {}

}

}

private void openFile(File file){

BufferedReader br = null;

String line = null;

this.ta.setText("");

this.f.setTitle(file.getAbsolutePath() + " - Notepad");

try {

br = new BufferedReader(new FileReader(file));

while((line = br.readLine()) != null){

this.ta.append(line + "\n");

}

} catch (IOException e) {

JOptionPane.showMessageDialog(this.f, e.getMessage());

} finally{

try {

br.close();

} catch (IOException e2) {}

}

}

public static void main(String[] args) {

new Notepad().display();

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

RandomAccess  - 한글 처리가 안된다.

import java.io.IOException;

import java.io.RandomAccessFile;


//한글 잘 될까요?

//length() - 사이즈, getFilePointer() - 현재포인터위치읽는, seek() - 원하는 위치에 포인터위치를 놓음

public class RandomAccessFileDemo {

public static void main(String[] args) {

String filePath = "src/RandomAccessFileDemo.java";

RandomAccessFile raf = null;

long size = 0;  //랜덤액새세는 처음나왔을때부터 사이즈가 long형

try {

raf = new RandomAccessFile(filePath, "r");

size = raf.length();

while(size > raf.getFilePointer()){ 

System.out.println(Utility.entoutf8(raf.readLine()));  //한 줄을 읽으면 포인터가 제일 마지막으로 이동, 한글이 나오게하기 위해 Utility클래스에서 따로 처리를 해줌.

}

} catch (IOException e) {

System.out.println(e.getMessage());

} finally{

try{

raf.close();

}catch(IOException ex){}

}

}

}

//랜덤액세스는 정말 쉽게 읽어들일 수 있으나, 한글이깨진다는 단점이 있다. 그래서 Utility class로 따로 처리를 해준다.


import java.io.UnsupportedEncodingException;


public class Utility {

public static String entoko(String en){

String ko = null;

try {

ko = new String(en.getBytes("ISO8859_1"), "KSC5601");

} catch (UnsupportedEncodingException e) {}

return ko;

}

public static String kotoen(String ko){

String en = null;

try {

en = new String(ko.getBytes("KSC5601"), "ISO8859_1");

} catch (UnsupportedEncodingException e) {}

return en;

}

public static String utf8toko(String utf8){

String ko = null;

try {

ko = new String(utf8.getBytes("UTF-8"), "KSC5601");

} catch (UnsupportedEncodingException e) {}

return ko;

}

public static String kotoutf8(String ko){

String utf8 = null;

try {

utf8 = new String(ko.getBytes("KSC5601"), "UTF-8");

} catch (UnsupportedEncodingException e) {}

return utf8;

}

public static String entoutf8(String en){

String utf8 = null;

try {

utf8 = new String(en.getBytes("ISO8859_1"), "UTF-8");

} catch (UnsupportedEncodingException e) {}

return utf8;

}

}

//new없이 접근하기 위해 모든 메소드를 static으로 만듬.

-----------------------------------------------------

Utility class는 위에 소스를 쓰고,

file로 demo.txt를 만들어서 아래와 같이 만들어줌.

89.5

true

5050

'A'

Hello

안녕하세요


import java.io.IOException;

import java.io.RandomAccessFile;



public class RandomAccessFileDemo1 {

public static void main(String[] args) throws IOException{

RandomAccessFile raf = null;

raf =new RandomAccessFile("src/demo.txt", "rw");

raf.seek(raf.length());    //파일 끝으로 이동

raf.writeUTF("\nWorld");  // '\n'을 넣고 글씨를 넣는 방법을 사용하면 안되는데, 이렇게 같이 넣어버리면 된다. 왜그런지는 잘몰라.

raf.writeUTF("\n한글연습");

raf.seek((long)0);     //파일 처음으로 이동

while(raf.length() > raf.getFilePointer()){

System.out.println(Utility.entoutf8(raf.readLine()));

}

raf.close();

}

}

출력:

89.5

true

5050

'A'

Hello

안녕하세요

World

한글연습

Thread

1. Thread Lifecycle

2. Race Condition

3. DeadLock

------------

1. Thread Lifecycle

public class SingleThread {

public static void main(String[] args) {

System.out.println(Thread.currentThread());

}

}

출력:

Thread[main,5,main]

//[이름, 우선순위, 그룹]

-----------------------------------

public class OneThread {

public static void main(String[] args) {

OneThread ot = new OneThread();

for(int i = 0 ; i < 10 ; i++)  System.out.println("main() --> " + i);

ot.run(); //running -> dead  run은 os스케쥴러가 일함

System.out.println("end main()");

}

void run(){

for(int i = 0 ; i < 10 ; i++)  System.out.println("run() --> " + i);

}

}

출력:

main() --> 0

main() --> 1

main() --> 2

main() --> 3

main() --> 4

main() --> 5

main() --> 6

main() --> 7

main() --> 8

main() --> 9

run() --> 0

run() --> 1

run() --> 2

run() --> 3

run() --> 4

run() --> 5

run() --> 6

run() --> 7

run() --> 8

run() --> 9

end main()

//run을 호출하기전에는 run은 실행하지 않아. 쓰레드가 오직 하나만 있는 경우임. 순서 예측 가능.

-------------------------------


public class TwoThread extends Thread{

public static void main(String[] args) {

TwoThread tt = new TwoThread();

for(int i = 0 ; i < 10 ; i++)  System.out.println("main() --> " + i);

tt.start(); //new->runnable 상태로. 메모리에 올리는 상태?

System.out.println("end main()");

}

@Override

public void run(){

for(int i = 0 ; i < 10 ; i++)  System.out.println("run() --> " + i);

}

}

출력:

main() --> 0

main() --> 1

main() --> 2

main() --> 3

main() --> 4

main() --> 5

main() --> 6

main() --> 7

main() --> 8

main() --> 9

end main()

run() --> 0

run() --> 1

run() --> 2

run() --> 3

run() --> 4

run() --> 5

run() --> 6

run() --> 7

run() --> 8

run() --> 9

//위코드와는 다르게 main이 끝나고 end main()을 찍어준 후에 run에가서 일함. 100번돌리면 100번 같지 않을 수 있다.

----아래의 코드로 바꿔주면


public class TwoThread extends Thread{

public static void main(String[] args) {

TwoThread tt = new TwoThread();

for(int i = 0 ; i < 10 ; i++)  System.out.println(Thread.currentThread().getName() + "--> " + i);

tt.start();

System.out.println("end main()");

}

@Override

public void run(){

for(int i = 0 ; i < 10 ; i++)  System.out.println(Thread.currentThread().getName() + " --> " + i);

}

}

출력:

main--> 0

main--> 1

main--> 2

main--> 3

main--> 4

main--> 5

main--> 6

main--> 7

main--> 8

main--> 9

end main()

Thread-0 --> 0

Thread-0 --> 1

Thread-0 --> 2

Thread-0 --> 3

Thread-0 --> 4

Thread-0 --> 5

Thread-0 --> 6

Thread-0 --> 7

Thread-0 --> 8

Thread-0 --> 9

각자활동하는 쓰레드의 이름이 다른 것을 볼 수 있다.

--------------------------------------------

//Thread의 자식

public class CreateThread extends Thread {

public static void main(String[] args) {

CreateThread ct = new CreateThread();

CreateThread ct1 = new CreateThread();

System.out.println(Thread.currentThread());

ct.start();

ct1.start();

}

@Override

public void run(){

System.out.println(Thread.currentThread());

}

}

//상속을 받으면 - 멀티상속이 안돼. 자식은 private빼고 다 볼 수 있다.

출력:

Thread[main,5,main]

Thread[Thread-0,5,main]

Thread[Thread-1,5,main]

-----------------------------------------------

public class CreateThread1 implements Runnable {

public static void main(String[] args) {

CreateThread1 ct = new CreateThread1();

CreateThread1 ct1 = new CreateThread1();

Thread t = new Thread(ct, "Duncan"); //runnable은 start메소드를 실행할 수없어서, 쓰레드를 선언하여.

Thread t1 = new Thread(ct1, "Sally"); //이름을 줄 수 있다.

t.start();

t1.start();

System.out.println(Thread.currentThread());

}

@Override

public void run() {

System.out.println(Thread.currentThread());

}


}

//단점은 내가 직접할 수 없고, 쓰레드를 선언하여 사용.

//상속을 받지 않았다는 점이 장점.

출력:

Thread[main,5,main]

Thread[Sally,5,main]

Thread[Duncan,5,main]

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

쓰레드를 안전하게 죽이는 방법.

//boolean type variable 이용하자.

//돌때마다 또 돌까요? 라고 물어보는 방법. 라인을 다돌아야 죽일 수 있다.

public class StopThread {

public static void main(String[] args) {

Demo d = new Demo();

Thread t = new Thread(d);

t.start();

System.out.println("Thread is starting...");

try{

Thread.sleep(1000);  //1초간 대기

}catch(InterruptedException ex){}

System.out.println("Thread stop...");

d.stop();

}

}

class Demo implements Runnable{

private boolean isStop;  //boolean변수는 기본초기값이 false

void stop(){

this.isStop = true;

}

@Override

public void run(){

//Thread 가 해야할 일

while(true){

try{

Thread.sleep(100); //0.1초 대기 후 

}catch(InterruptedException ex){}

System.out.println("I'm alive...");

if(this.isStop) break;

}

System.out.println("I'm dead...");

}

}

출력:

Thread is starting...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

Thread stop...

I'm alive...    <-여기서 바로 안죽고 한번 더찍어주는 이유는 if문에서 죽었는지 확인하는 시간필요. 그래서 단점은 바로죽지않는다는.

I'm dead...

--------------------------------------

//Exception 이용하자.

//100라인까지 가는상황에서 20라인에서 죽일 수 있다.장점: 바로 죽일 수 있다.

public class StopThread1 {

public static void main(String[] args) {

Demo1 d = new Demo1();

Thread t = new Thread(d);

t.start();

System.out.println("Thread is starting...");

try{

Thread.sleep(100);  //0.1초간 대기

}catch(InterruptedException ex){}

System.out.println("Thread stop...");

t.interrupt();  //InterruptedException throw

}

}

class Demo1 implements Runnable{

@Override

public void run(){

//Thread 가 해야할 일

try{

while(true){

Thread.sleep(10);   //0.01초

System.out.println("I'm alive...");

}

}catch(InterruptedException ex){

System.out.println("I'm dead...");

}

}

}

출력:

Thread is starting...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

I'm alive...

Thread stop...

I'm dead...

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

데몬 쓰레드

public class DaemonThread {

public static void main(String[] args) {

Thread t = new Thread(){

@Override

public void run(){

//Thread 가 해야할 일

try {

Thread.sleep(20000);   //20초 대기

} catch (Exception e) {}

System.out.println("Thread is over...");

}

};

t.start();

try {

Thread.sleep(5000);   //5초간 대기

} catch (Exception e) {}

System.out.println("main() is over...");

}

}

출력:

main() is over...

Thread is over...

//메인은 5초뒤에 중지. 쓰레드는 그 뒤로 15초뒤에 중지.

//메인이 끝나고 프로그램이 끝나는 것이 아니라, 안의 모든 쓰레드가 끝나야 종료.

--------------만약

t.start()위에 t.setDaemon(true);를 써주면 이 프로그램은 데몬쓰레드를 의미한다.

데몬쓰레드는 메인이 끝이면 프로그램이 끝이다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Join

public class JoinDemo {

public static void main(String[] args) {

Thread t = new Thread(){

@Override

public void run(){

//Thread 가 해야할 일

try {

Thread.sleep(5000);   //5초간 대기

System.out.println("I'm Thread...");

} catch (Exception e) {} //5초가 보장하지 않을 경우의 익셉션

}

};

t.start();

try{

t.join();  //t라는 thread가 끝나면 join하겠다. ()안에 숫자넣으면 그 시간만큼.

}catch (Exception e){}

System.out.println("I'm main()");

}

}

출력:

I'm Thread...

I'm main()

//t.join을 써주지 않으면 당연히 I'm main()이 먼저 출력되지만, join을 써줌으로써 출력순서가 바뀜.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Priority


public class PriorityDemo {

public static void main(String[] args) {

System.out.println("MAX : " + Thread.MAX_PRIORITY); 

System.out.println("MIN : " + Thread.MIN_PRIORITY);

System.out.println("NORM : " + Thread.NORM_PRIORITY);

}

}

출력:

MAX : 10

MIN : 1

NORM : 5

-----------------


public class PriorityDemo {

public static void main(String[] args) {

//System.out.println("MAX : " + Thread.MAX_PRIORITY); 

//System.out.println("MIN : " + Thread.MIN_PRIORITY);

//System.out.println("NORM : " + Thread.NORM_PRIORITY);

Test t = new Test("Duncan");

t.setPriority(Thread.MIN_PRIORITY);

Test t1 = new Test("Sally");

t1.setPriority(Thread.MAX_PRIORITY);

t.start();

t1.start();

}

}

class Test extends Thread{

Test(String name){

super(name);

}

@Override

public void run(){

System.out.println(Thread.currentThread());

}

}

출력:

Thread[Duncan,1,main]

Thread[Sally,10,main]

//우선순위를 10을줬음에도 출력이 바뀌지 않았다. priority는 잘 안되는 것을 볼 수 있다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

sleep과 yield

public class SleepDemo extends Thread{

SleepDemo(String name) { super(name);  }

public static void main(String[] args) {

SleepDemo sd = new SleepDemo("Duncan");

SleepDemo sd1 = new SleepDemo("Sally");

sd.start();    sd1.start();

}

@Override

public void run(){

//Thread가 해야할 일

for(int i = 0 ; i < 20 ; i++){

//Thread.yield();

try{

Thread.sleep(1000);

}catch(Exception e){}

System.out.println(Thread.currentThread().getName() + " --> " + i);

}

}

}

//처음에 sleep이나 yield가 없는경우

Duncan --> 0

Duncan --> 1

Sally --> 0

Duncan --> 2

Sally --> 1

Duncan --> 3

이렇게 시작하고 순서없이 출력된다. 이 결과는 실행때마다 출력 순서가 다르다.

출력부분 위에  Thread.yield(); 를 추가해주면 서로 양보하기 때문에 위와 같이 순서없이 출력되는 것 같다.

그러면 sleep을 주면 출력후 1초간 쉬기 때문에

Duncan --> 0

Sally --> 0

Duncan --> 1

Sally --> 1

Duncan --> 2

Sally --> 2

Duncan --> 3

Sally --> 3

위와 같이 하나씩 출력하는 것을 볼  수 있다. 하지만 가끔 Duncan이 두번연속 출력되는 것도 있지만 숫자는 00 11 이런식으로 바뀌지 않는다.

--------------------------------------------------------

쓰레드를 이용하여 시계만들기

import java.awt.BorderLayout;

import java.awt.Canvas;

import java.awt.Container;

import java.awt.Font;

import java.awt.Graphics;

import java.util.Calendar;


import javax.swing.JFrame;


public class MyClock extends Thread {

private JFrame f;

private MyCanvas mc;

private Container con;

private MyClock(){

this.f = new JFrame("My Digital Clock");

this.con = this.f.getContentPane();

mc = new MyCanvas();

}

private void display(){

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //끝내면 끝나게.

Font font = new Font("Loma", Font.BOLD, 50);

this.mc.setFont(font);

this.con.setLayout(new BorderLayout());

this.con.add("Center", this.mc);

this.f.setSize(500,200);

this.f.setLocationRelativeTo(null);

this.f.setVisible(true);

}

private class MyCanvas extends Canvas{

private Calendar cal;

@Override

public void paint(Graphics g){

cal = Calendar.getInstance();

String str = String.format("%tT", cal);  //'T'를 찍으면 "%tH:%tM:%tS"를 자동으로

g.drawString(str, 50, 50);

}

}

@Override

public void run(){

//Thread가 해야할 일

try{

while(true){

Thread.sleep(1000);

this.mc.repaint();

}

}catch(InterruptedException e) {}

}

public static void main(String[] args) {

//new MyClock().display(); //display와 쓰레드를 시작해줘야 하기 때문에 이렇게 쓰면 복잡해지니. 하나쓸때만 편함.

MyClock clock = new MyClock();

clock.display();

clock.start();


}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Thread group


public class ThreadGruopDemo {

public static void main(String[] args) {

System.out.println(Thread.currentThread().getThreadGroup());

ThreadGroup group1 = new ThreadGroup("Group1");

ThreadGroup group2 = new ThreadGroup(Thread.currentThread().getThreadGroup(),"Group2");  //부모그룹, 내그룹이름

ThreadGroup group3 = new ThreadGroup(group1, "Group3");

Thread t1 = new Thread(group1, "Thread1");

Thread t2 = new Thread(group2, "Thread2");

Thread t3 = new Thread(group3, "Thread3");

System.out.println(t1);

System.out.println(t2);

System.out.println(t3);

int count = Thread.currentThread().getThreadGroup().activeCount();

int groupCount = Thread.currentThread().getThreadGroup().activeGroupCount();

System.out.println("count = " + count);

System.out.println("group count = " + groupCount);

Thread.currentThread().getThreadGroup().list();  //list()는 void형임

}

}

출력:

java.lang.ThreadGroup[name=main,maxpri=10]

Thread[Thread1,5,Group1]

Thread[Thread2,5,Group2]

Thread[Thread3,5,Group3]

count = 1

group count = 3

java.lang.ThreadGroup[name=main,maxpri=10]

    Thread[main,5,main]

    java.lang.ThreadGroup[name=Group1,maxpri=10]

        java.lang.ThreadGroup[name=Group3,maxpri=10]

    java.lang.ThreadGroup[name=Group2,maxpri=10]

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Thread는 stack을 제외하고 heap, method  area, context pool 에서는 자원을 공유함.

자원공유때문에 race condition문제가 발생.


Syncronized


전혀 동기화처리가 되지않은 ATM


public class ATM  implements Runnable{

private int balance;

ATM(){

this.balance = 10000;

}

private void withdraw(int howmuch){

if(this.balance <= 0){

System.out.print("[" + Thread.currentThread().getName() +"] --> ");

System.out.println(" --> 잔액이 없습니다.");

}else{

this.balance -= howmuch;

System.out.println("[" + Thread.currentThread().getName() +"] -->" +  this.balance);

}

}

@Override

public void run(){

//Thread 가 해야할 일

for(int i = 0 ; i < 10 ; i++){

try{

Thread.sleep(1000);

}catch(InterruptedException ex){}

if(this.balance > 0) withdraw(1000);

else break;

}

}

}



public class ATMDemo {

public static void main(String[] args) {

ATM atm = new ATM();

Thread mother = new Thread(atm, "mother");

Thread son = new Thread(atm, "son");

mother.start();

son.start();

}

}


출력:

[mother] -->9000

[son] -->9000

[mother] -->8000

[son] -->7000

[mother] -->6000

[son] -->5000

[son] -->4000

[mother] -->4000

[son] -->3000

[mother] -->2000

[son] -->1000

[mother] -->0

//돌릴때마다 다르게 나옴. 여기서는 12번 인출을 해서 은행입장에서는 손해가 보게된다.

-----------------------------

version up  - ATM v-1


public class ATM1  implements Runnable{

private int balance;

ATM1(){

this.balance = 10000;

}

private /*synchronized*/ void withdraw(int howmuch){  //메소드를 동기화할 때 이렇게 사용.

if(this.balance <= 0){

System.out.print("[" + Thread.currentThread().getName() +"] --> ");

System.out.println(" --> 잔액이 없습니다.");

}else{

this.balance -= howmuch;

System.out.println("[" + Thread.currentThread().getName() +"] -->" +  this.balance);

}

}

@Override

public void run(){

//Thread 가 해야할 일

for(int i = 0 ; i < 5 ; i++){

synchronized(this){  //동기화 블럭

try{

Thread.sleep(1000);

}catch(InterruptedException ex){}

if(this.balance > 0) withdraw(1000);

else break;

}

}

}

}



public class ATMDemo {

public static void main(String[] args) {

ATM1 atm = new ATM1();

Thread mother = new Thread(atm, "mother");

Thread son = new Thread(atm, "son");

mother.start();

son.start();

}

}

출력:

[mother] -->9000

[mother] -->8000

[mother] -->7000

[mother] -->6000

[mother] -->5000

[son] -->4000

[son] -->3000

[son] -->2000

[son] -->1000

[son] -->0

//동시에 하나의 쓰레드만 사용하여, 엄마먼저 끝내고, 아들이 실행. 엄마가 실행되는동안 다른 쓰레드는 대기상태.

//락을 걸면 좋은 점은 한 쓰레드만 들어올 수 있다. 쓰는 쓰레드는 열쇠를 들고 있다가 다쓰면 반납하고, 그 다음 쓰레드가 사용한다.

---------------------------

ATM v-2

데드락문제 해결


public class ATM2  implements Runnable{

private int balance;

ATM2(){

this.balance = 10000;

}

private /*synchronized*/ void withdraw(int howmuch){  //메소드를 동기화할 때 이렇게 사용.

if(this.balance <= 0){

System.out.print("[" + Thread.currentThread().getName() +"] --> ");

System.out.println(" --> 잔액이 없습니다.");

}else{

this.balance -= howmuch;

System.out.println("[" + Thread.currentThread().getName() +"] -->" +  this.balance);

}

}

@Override

public void run(){

//Thread 가 해야할 일

for(int i = 0 ; i < 10 ; i++){

synchronized(this){  //동기화 블럭

try{

Thread.sleep(1000);

}catch(InterruptedException ex){}

if(this.balance > 0) withdraw(1000);

else break;

if(this.balance == 2000 || this.balance == 4000 || this.balance == 6000 || this.balance == 8000) {

try{

this.wait();

}catch(InterruptedException e) {}

} else{

this.notify();

}

}

}

}

}




public class ATMDemo {

public static void main(String[] args) {

ATM2 atm = new ATM2();

Thread mother = new Thread(atm, "mother");

Thread son = new Thread(atm, "son");

mother.start();

son.start();

}

}

출력:

[mother] -->9000

[mother] -->8000

[son] -->7000

[son] -->6000

[mother] -->5000

[mother] -->4000

[son] -->3000

[son] -->2000

[mother] -->1000

[mother] -->0

//2000원마다 쓰레드를 변경.




===============================================



열차.zip



public class Calc {

private Customer customer;

public Calc(Customer customer){

this.customer = customer;

}

public void calc(){

String pCode = this.customer.getPcode();

this.customer.setRegion(this.getPlaceName(pCode));

int distance = this.getPlaceDistance(pCode);

String gender = (customer.getJumin2().trim().charAt(0) == '1') ? "남자" : "여자";

this.customer.setGender(gender);

String tCode = customer.getTscode().trim().substring(0,2);

String tName = this.getTrainName(tCode);

customer.setTname(tName);

String seatName = this.getSeatName(tCode);

customer.setSname(seatName);

String ppCode = customer.getPpcode();

customer.setKind(this.getKindName(ppCode));

double rate = this.getRate(ppCode);

int danga = this.getDanga(tName, seatName);

int price = distance * danga;

int premium = (int)(price * rate);

customer.setPrice(premium);

int charge = price - premium;

customer.setCharge(charge);

}

private String getPlaceName(String pCode){

String pName = null;

switch(pCode){

case "CA": pName = "서울"; break;

case "CB": pName = "부산"; break;

case "CC": pName = "대구"; break;

case "CD": pName = "광주"; break;

}

return pName;

}

private int getPlaceDistance(String pCode){

int distance = 0;

switch(pCode){

case "CA": distance = 400 ; break;

case "CB": distance = 50 ; break;

case "CC": distance = 110 ; break;

case "CD": distance = 180 ; break;

}

return distance;

}

private String getTrainName(String tCode){

String tName = null;

switch(tCode){

case "TA" : tName = "새마을호" ; break;

case "TB" : tName = "무궁화호" ; break;

case "TC" : tName = "통일호"; break;

}

return tName;

}

private String getSeatName(String tCode){

String seatName = null;

switch(tCode){

case "TA" : seatName = "특실" ; break;

case "TB" : seatName = "1등칸" ; break;

case "TC" : seatName = "보통칸"; break;

}

return seatName;

}

private String getKindName(String ppCode){

String kindName = null;

switch(ppCode){

case "P0" : kindName = "일반" ; break;

case "P1" : kindName = "소인" ; break;

case "P2" : kindName = "군인"; break;

case "P3" : kindName = "장애인"; break;

}

return kindName;

}

private double getRate(String ppCode){

double rate = 0.0;

switch(ppCode){

case "P0" : rate = 0.0 ; break;

case "P1" : rate = 0.5 ; break;

case "P2" : rate = 0.3 ; break;

case "P3" : rate = 0.8 ; break;

}

return rate;

}

private int getDanga(String tName, String seatName){

int danga = 0;

switch(tName){

case "새마을호" : danga = (seatName.equals("특실"))? 80 : 

                         (seatName.equals("1등칸")) ? 65 : 50; break;

case "무궁화호" : danga = (seatName.equals("특실"))? 60 : 

                                          (seatName.equals("1등칸")) ? 55 : 40; break;

case "통일호" :  danga = 30; break;

}

return danga;

}

}





public class Customer {

private int id;

private String tscode;   //열차코드

private String pcode;    //장소코드

private String jumin1;   //주민번호1

private String jumin2;   //주민번호2

private String ppcode;  //할증코드

private String region;   //장소명

private String gender;  //성별

private String tname;   //열차명

private String sname;   //좌석명

private String kind;       //할증종류

private int price;          //할인액

private int charge;       //차비

public Customer(){}

public Customer(String tscode, String pcode, String jumin1,String jumin2, String ppcode) {

this.tscode = tscode;

this.pcode = pcode;

this.jumin1 = jumin1;

this.jumin2 = jumin2;

this.ppcode = ppcode;

}

@Override

public String toString(){

return String.format("%2d%10s%7s%10s%10s%10s%,15d%,15d\n",

                    this.id, this.region, this.gender, this.tname,

                    this.sname,this.kind, this.price,this.charge);

}

public String getTscode() {

return tscode;

}

public void setTscode(String tscode) {

this.tscode = tscode;

}

public String getPcode() {

return pcode;

}

public void setPcode(String pcode) {

this.pcode = pcode;

}

public String getJumin1() {

return jumin1;

}

public void setJumin1(String jumin1) {

this.jumin1 = jumin1;

}

public String getJumin2() {

return jumin2;

}

public void setJumin2(String jumin2) {

this.jumin2 = jumin2;

}

public String getPpcode() {

return ppcode;

}

public void setPpcode(String ppcode) {

this.ppcode = ppcode;

}

public String getRegion() {

return region;

}

public void setRegion(String region) {

this.region = region;

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender;

}

public String getTname() {

return tname;

}

public void setTname(String tname) {

this.tname = tname;

}

public String getSname() {

return sname;

}

public void setSname(String sname) {

this.sname = sname;

}

public String getKind() {

return kind;

}

public void setKind(String kind) {

this.kind = kind;

}

public int getPrice() {

return price;

}

public void setPrice(int price) {

this.price = price;

}

public int getCharge() {

return charge;

}

public void setCharge(int charge) {

this.charge = charge;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

}




import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;


public class CustomerController implements ActionListener {

private JPanel panel;

private JTextField tfTCode, tfPCode, tfJumin1, tfJumin2, tfPpCode;

private Vector<Customer> vector;

private int count;

public CustomerController(JPanel panel, Vector<Customer> vector,

                             JTextField tfTCode, JTextField tfPCode, 

                             JTextField tfJumin1, JTextField tfJumin2, JTextField tfPpCode){

this.panel = panel;     this.vector = vector;

this.tfTCode = tfTCode;           this.tfPCode = tfPCode;

this.tfJumin1 = tfJumin1;    this.tfJumin2 = tfJumin2;   this.tfPpCode = tfPpCode;

}

@Override

public void actionPerformed(ActionEvent e) {

Customer customer = customerAdd();

customerCalc(customer);

customer.setId(++count);

this.vector.addElement(customer);

JOptionPane.showMessageDialog(this.panel, "1 Register Success!!!", "메시지",

                                      JOptionPane.INFORMATION_MESSAGE);

}

private Customer customerAdd(){

Customer customer = new Customer(this.tfTCode.getText().trim(), this.tfPCode.getText().trim(),

                        this.tfJumin1.getText().trim(), this.tfJumin2.getText().trim(),

                        this.tfPpCode.getText().trim());

this.tfTCode.setText("");   this.tfPCode.setText("");

this.tfJumin1.setText("");  this.tfJumin2.setText("");

this.tfPpCode.setText("");

return customer;

}

private void customerCalc(Customer customer){

Calc calc = new Calc(customer);

calc.calc();

}

}




import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.sql.SQLException;

import java.util.Vector;


import javax.swing.JPanel;

import javax.swing.JTable;


public class DisplayController implements ActionListener {

private JTable table1, table2, table3, table4;

private Vector<Customer> vector;

public DisplayController(Vector<Customer> vector, JTable table1, JTable table2, JTable table3, JTable table4){

this.vector = vector;

this.table1 = table1;

this.table2 = table2;

this.table3 = table3;

this.table4 = table4;

}

@Override

public void actionPerformed(ActionEvent e) {

this.table1.setModel(

new MyTableModel1(Utility.getRegionCustomer(this.vector, "서울")));

this.table2.setModel(

new MyTableModel1(Utility.getRegionCustomer(this.vector, "부산")));

this.table3.setModel(

new MyTableModel1(Utility.getRegionCustomer(this.vector, "대구")));

this.table4.setModel(

new MyTableModel1(Utility.getRegionCustomer(this.vector, "광주")));

}

}





import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.GridLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.border.BevelBorder;

import javax.swing.border.TitledBorder;


public class InputPanel extends JPanel {

private JButton btnRegister;

private JTextField tfTCode, tfPCode, tfJumin1, tfJumin2, tfPpCode;

private JLabel labelTCode, labelPCode, labelJumin, labelPpCode;

private Font font;

private Vector<Customer> vector;

public InputPanel(Vector<Customer> vector){

this.vector = vector;

this.font = new Font("Monospace", Font.BOLD, 20);

this.setLayout(new FlowLayout());

this.add(this.getPanel()); 

}

private JPanel getPanel(){

JPanel p = new JPanel();

p.setLayout(new BorderLayout());

p.setBorder(new TitledBorder(

                   new BevelBorder(BevelBorder.RAISED), "열차예매 정보 입력"));

p.add("South", this.getSouthPanel());

p.add("West", this.getWestPanel());

p.add("Center", this.getCenterPanel());

CustomerController controller = new CustomerController(this,this.vector, this.tfTCode, this.tfPCode, 

                                       this.tfJumin1, this.tfJumin2, this.tfPpCode);

this.btnRegister.addActionListener(controller);

return p;

}

private JPanel getCenterPanel(){

JPanel p = new JPanel();

p.setLayout(new GridLayout(4,1,10,10));

p.add(this.tfTCode = new JTextField(15));

tfTCode.setFont(this.font);

p.add(this.tfPCode = new JTextField(15));

tfPCode.setFont(this.font);

p.add(this.tfJumin1 = new JTextField(7));

tfJumin1.setFont(this.font);

p.add(this.tfJumin2 = new JTextField(8));

tfJumin2.setFont(this.font);

JPanel p1 = new JPanel();

JLabel labelDash = new JLabel("-");

labelDash.setFont(this.font);

p1.add(this.tfJumin1);  p1.add(labelDash);  p1.add(this.tfJumin2);  //위에있는 것을 다시 정의하면 그 공간이 사라지고 새로운 공간을 넣음.

p.add(p1);

p.add(this.tfPpCode = new JTextField(15));

tfPpCode.setFont(this.font);

return p;

}

private JPanel getWestPanel(){

JPanel p = new JPanel();

p.setLayout(new GridLayout(4,1,10,10));

p.add(this.labelTCode = new JLabel("열차 좌석 코드 : ", JLabel.RIGHT));    

this.labelTCode.setFont(this.font);

p.add(this.labelPCode = new JLabel("장소 코드 : ", JLabel.RIGHT));   

this.labelPCode.setFont(this.font);

p.add(this.labelJumin = new JLabel("주민등록번호 : ", JLabel.RIGHT));   

this.labelJumin.setFont(this.font);

p.add(this.labelPpCode = new JLabel("할증 코드 : ", JLabel.RIGHT));     

this.labelPpCode.setFont(this.font);

return p;

}

private JPanel getSouthPanel(){

JPanel p = new JPanel();

p.add(btnRegister = new JButton("    예약하기    "));

this.btnRegister.setFont(this.font);

this.btnRegister.setBorder(new BevelBorder(BevelBorder.RAISED));

return p;

}

}





import java.awt.Container;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JTabbedPane;


public class Main {

private JFrame f;

private JTabbedPane pane;

private Container con;

private Vector<Customer> vector;

private void display(){

f = new JFrame("열차예매관리프로그램");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

con = f.getContentPane();

pane = new JTabbedPane();

this.vector = new Vector<Customer>(1,1);

pane.add(new InputPanel(this.vector), "데이터입력");

pane.add(new OutputPanel(this.vector), "데이터출력");

con.add(pane, "Center");

f.setSize(700,900);

f.setVisible(true);

}

public static void main(String[] args) {

new Main().display();

}

}





import java.util.Vector;


import javax.swing.table.DefaultTableModel;


public class MyTableModel1 extends DefaultTableModel{

private Vector<Customer> vector;   //서울고객명단

public MyTableModel1(Vector<Customer> vector){

this.vector = vector;

dataAddToTable();

}

private void dataAddToTable(){

String [] columnArray = {"번호", "지역", "성별", "열차명", "좌석", "할증종류", "할인액", "차비"};

Vector<String> colVector = new Vector<String>(1,1);

for(String str : columnArray) colVector.addElement(str);

Vector<Object> dataVector = new Vector<Object>(1,1);

for(int i = 0 ; i < this.vector.size(); i++){

Customer customer = this.vector.get(i);

Vector<String> row = new Vector<String>(1,1);

row.addElement(String.valueOf(customer.getId()));

row.addElement(customer.getRegion());

row.addElement(customer.getGender());

row.addElement(customer.getTname());

row.addElement(customer.getSname());

row.addElement(customer.getKind());

row.addElement(String.valueOf(customer.getPrice()));

row.addElement(String.valueOf(customer.getCharge()));

dataVector.addElement(row);

}

this.setDataVector(dataVector, colVector);

}

}




import java.util.Vector;


import javax.swing.table.DefaultTableModel;


public class MyTableModel2 extends DefaultTableModel{

private Vector<Customer> vector;   //부산고객명단

public MyTableModel2(Vector<Customer> vector){

this.vector = vector;

dataAddToTable();

}

private void dataAddToTable(){

String [] columnArray = {"번호", "지역", "성별", "열차명", "좌석", "할증종류", "할인액", "차비"};

Vector<String> colVector = new Vector<String>(1,1);

for(String str : columnArray) colVector.addElement(str);

Vector<Object> dataVector = new Vector<Object>(1,1);

for(int i = 0 ; i < this.vector.size(); i++){

Customer customer = this.vector.get(i);

Vector<String> row = new Vector<String>(1,1);

row.addElement(String.valueOf(customer.getId()));

row.addElement(customer.getRegion());

row.addElement(customer.getGender());

row.addElement(customer.getTname());

row.addElement(customer.getSname());

row.addElement(customer.getKind());

row.addElement(String.valueOf(customer.getPrice()));

row.addElement(String.valueOf(customer.getCharge()));

dataVector.addElement(row);

}

this.setDataVector(dataVector, colVector);

}

}




import java.util.Vector;


import javax.swing.table.DefaultTableModel;


public class MyTableModel3 extends DefaultTableModel{

private Vector<Customer> vector;   //대구고객명단

public MyTableModel3(Vector<Customer> vector){

this.vector = vector;

dataAddToTable();

}

private void dataAddToTable(){

String [] columnArray = {"번호", "지역", "성별", "열차명", "좌석", "할증종류", "할인액", "차비"};

Vector<String> colVector = new Vector<String>(1,1);

for(String str : columnArray) colVector.addElement(str);

Vector<Object> dataVector = new Vector<Object>(1,1);

for(int i = 0 ; i < this.vector.size(); i++){

Customer customer = this.vector.get(i);

Vector<String> row = new Vector<String>(1,1);

row.addElement(String.valueOf(customer.getId()));

row.addElement(customer.getRegion());

row.addElement(customer.getGender());

row.addElement(customer.getTname());

row.addElement(customer.getSname());

row.addElement(customer.getKind());

row.addElement(String.valueOf(customer.getPrice()));

row.addElement(String.valueOf(customer.getCharge()));

dataVector.addElement(row);

}

this.setDataVector(dataVector, colVector);

}

}




import java.util.Vector;


import javax.swing.table.DefaultTableModel;


public class MyTableModel4 extends DefaultTableModel{

private Vector<Customer> vector;   //광주고객명단

public MyTableModel4(Vector<Customer> vector){

this.vector = vector;

dataAddToTable();

}

private void dataAddToTable(){

String [] columnArray = {"번호", "지역", "성별", "열차명", "좌석", "할증종류", "할인액", "차비"};

Vector<String> colVector = new Vector<String>(1,1);

for(String str : columnArray) colVector.addElement(str);

Vector<Object> dataVector = new Vector<Object>(1,1);

for(int i = 0 ; i < this.vector.size(); i++){

Customer customer = this.vector.get(i);

Vector<String> row = new Vector<String>(1,1);

row.addElement(String.valueOf(customer.getId()));

row.addElement(customer.getRegion());

row.addElement(customer.getGender());

row.addElement(customer.getTname());

row.addElement(customer.getSname());

row.addElement(customer.getKind());

row.addElement(String.valueOf(customer.getPrice()));

row.addElement(String.valueOf(customer.getCharge()));

dataVector.addElement(row);

}

this.setDataVector(dataVector, colVector);

}

}




import java.awt.BorderLayout;

import java.awt.Font;

import java.awt.GridLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;


public class OutputPanel extends JPanel {

private JButton btnDisplay, btnSave;

private JTable table1, table2, table3, table4;

private JScrollPane pane1, pane2, pane3, pane4;

private Vector<Customer> vector;

private Font font;

public OutputPanel(Vector<Customer> vector){

this.vector = vector;

this.setLayout(new BorderLayout());

this.font = new Font("Monospace", Font.BOLD, 15);

this.add("North", this.getNorthPanel());

this.add("Center", this.getCenterPanel());

btnDisplay.addActionListener(new DisplayController(this.vector, table1, table2, table3, table4));

btnSave.addActionListener(new SaveAction(this, this.vector));

}

private JPanel getNorthPanel(){

JPanel p = new JPanel();

p.add(this.btnDisplay = new JButton("Display"));

p.add(this.btnSave = new JButton("Backup"));

return p;

}

private JPanel getCenterPanel(){

JPanel p = new JPanel();

p.setLayout(new GridLayout(4,1,10,0));

this.table1 = new JTable();

this.table1.setRowHeight(25);

this.table1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

this.table1.setFont(this.font);

this.pane1 = new JScrollPane(this.table1);

this.table2 = new JTable();

this.table2.setRowHeight(25);

this.table2.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

this.table2.setFont(font);

this.pane2 = new JScrollPane(this.table2);

this.table3 = new JTable();

this.table3.setRowHeight(25);

this.table3.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

this.table3.setFont(this.font);

this.pane3 = new JScrollPane(this.table3);

this.table4 = new JTable();

this.table4.setRowHeight(25);

this.table4.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

this.table4.setFont(this.font);

this.pane4 = new JScrollPane(this.table4);

p.add(pane1);

p.add(pane2);

p.add(pane3);

p.add(pane4);

return p;

}

}





import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import java.util.Vector;


import javax.swing.JFileChooser;

import javax.swing.JOptionPane;

import javax.swing.JPanel;


public class SaveAction implements ActionListener {

private JPanel panel;

private Vector<Customer> vector;

public SaveAction(JPanel panel, Vector<Customer> vector){

this.panel = panel;

this.vector = vector;

}

@Override

public void actionPerformed(ActionEvent e) {

JFileChooser jc = new JFileChooser(".");

int choice = jc.showSaveDialog(this.panel);

if(choice == JFileChooser.CANCEL_OPTION) return;

java.io.File file = jc.getSelectedFile();

BufferedWriter bw = null;

try{

bw = new BufferedWriter(new FileWriter(file));

printLabel(bw);

if(this.vector.size() == 0){

JOptionPane.showMessageDialog(this.panel, "데이터가 없습니다", "Warning", 

JOptionPane.WARNING_MESSAGE);

return;

}

for(int i = 0 ; i < this.vector.size() ; i++){

Customer customer = vector.get(i);

bw.write(customer.toString());

bw.flush();

}

JOptionPane.showMessageDialog(this.panel, file.getAbsolutePath() + "에 잘 저장됐습니다.");

}catch(IOException ex){

JOptionPane.showMessageDialog(this.panel, ex.getMessage(), "Error", 

JOptionPane.ERROR_MESSAGE);

}finally{

try{

bw.close();

}catch(IOException ex){}

}

}

private void printLabel(BufferedWriter bw) throws IOException {

bw.write("                       <<금일 지역별 열차 예약 현황>>\n");

bw.write("--------------------------------------------------------------------------------\n");

bw.write("번호     지역     성별      열차명         좌석     할증종류        할인액          차비\n");

bw.write("--------------------------------------------------------------------------------\n");

}


}





import java.util.Vector;



public class Utility {

public static Vector<Customer> getRegionCustomer(Vector<Customer> original, String region){

Vector<Customer> temp = new Vector<Customer>(1,1);

for(int i = 0 ; i < original.size() ; i++){

Customer customer = original.get(i);

if(customer.getRegion().equals(region))

temp.addElement(customer);

}

return temp;

}

}


성적관리프로그램 V2.0

public class Student implements Comparable<Student> {

private String hakbun, name;

private int kor, eng, mat, edp, tot, ranking;

private double avg;

private char grade;

public Student(String hakbun, String name, int kor, int eng, int mat, int edp) {

this.hakbun = hakbun;

this.name = name;

this.kor = kor;

this.eng = eng;

this.mat = mat;

this.edp = edp;

this.ranking = 1;

}

@Override

public int compareTo(Student s){

return this.getTot() - s.getTot();

}

public String [] toArray(){

String [] array = new String[10];

array[0] = this.hakbun;   array[1] = this.name;

array[2] = String.valueOf(this.kor);       array[3] = String.valueOf(this.eng);     

array[4] = String.valueOf(this.mat);       array[5] = String.valueOf(this.edp);     

array[6] = String.valueOf(this.tot);         array[7] = String.valueOf(this.avg);

array[8] = String.valueOf(this.grade);    array[9] = String.valueOf(this.ranking);          

return array;

}

@Override

public String toString(){

return String.format("%-10s%7s%5d%5d%5d%5d%5d%10.2f%5c%5d\n",

this.hakbun, this.name, this.kor, this.eng, this.mat, this.edp,

this.tot, this.avg, this.grade, this.ranking);

}

public int getTot() {

return tot;

}

public void setTot(int tot) {

this.tot = tot;

}

public int getRanking() {

return ranking;

}

public void setRanking(int ranking) {

this.ranking = ranking;

}

public double getAvg() {

return avg;

}

public void setAvg(double avg) {

this.avg = avg;

}

public char getGrade() {

return grade;

}

public void setGrade(char grade) {

this.grade = grade;

}

public int getKor() {

return kor;

}

public int getEng() {

return eng;

}

public int getMat() {

return mat;

}

public int getEdp() {

return edp;

}

}






import java.awt.BorderLayout;

import java.awt.Font;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;

import javax.swing.border.TitledBorder;


public class InputPanel extends JPanel {

private Vector<Student> vector;

private JTextField tf;

private JButton btnBrowse, btnLoad;

private Font font;

private JLabel lblPath;

private JPanel p;

private JFrame f;

private JTabbedPane tab;

InputPanel(Vector<Student> vector, JFrame f, JTabbedPane tab){

this.vector = vector;

this.f = f;

this.tab = tab;

this.font = new Font("NanumGotic", Font.PLAIN, 15);

tf = new JTextField(20);   tf.setFont(font);

tf.setEditable(false);

btnBrowse = new JButton("Browse...");

btnBrowse.addActionListener(new InputAction(this.vector, this.tf, this.f, this.tab));

btnBrowse.setFont(font);

btnLoad = new JButton("Load");

btnLoad.addActionListener(new InputAction(this.vector, this.tf, this.f, this.tab));

btnLoad.setFont(font);

p = this.getPanel();

this.add(this.p);

}

private JPanel getPanel(){

JPanel pTemp = new JPanel();

pTemp.setLayout(new BorderLayout(20,40));

pTemp.setBorder(new TitledBorder("성적파일경로"));

pTemp.add(this.tf, "Center");

pTemp.add(this.btnBrowse, "East");

pTemp.add(this.btnLoad, "South");

return pTemp;

}

}









import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.File;

import java.io.FileNotFoundException;

import java.util.NoSuchElementException;

import java.util.Scanner;

import java.util.StringTokenizer;

import java.util.Vector;


import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;


public class InputAction implements ActionListener {

private Vector<Student> vector;

private JTextField tf;

private JFrame f;

private JTabbedPane tab;

public InputAction(Vector<Student> vector, JTextField tf, JFrame f, JTabbedPane tab){

this.vector = vector;

this.tf = tf;

this.f = f;

this.tab = tab;

}

@Override

public void actionPerformed(ActionEvent evt){

switch(evt.getActionCommand()){

case "Browse..." : setFile(); break;

case "Load" : input(this.tf.getText()); break;

}

}

private void setFile(){

JFileChooser jc = new JFileChooser(".");

int choice = jc.showOpenDialog(null);

if(choice == JFileChooser.CANCEL_OPTION){

JOptionPane.showMessageDialog(this.f, "반드시 파일을 선택해야 합니다", 

"File Not Found", JOptionPane.ERROR_MESSAGE);

}else if(choice == JFileChooser.APPROVE_OPTION){

File file = jc.getSelectedFile();

this.tf.setText(file.getAbsolutePath());

}

}

private void input(String path){   //Load 버튼을 눌렀을 때

if(this.tf.getText() == null || this.tf.getText().length() == 0){

//경로가 선택되지 않았다면

JOptionPane.showMessageDialog(this.f, "반드시 파일을 선택해야 합니다", 

"File Not Found", JOptionPane.ERROR_MESSAGE);

return;

}

StringTokenizer st = null;

String line = null;

Scanner scan = null;

try{

scan = new Scanner(new File(path));

this.vector.clear();

while((line = scan.nextLine()) != null){

//System.out.println(line);

st = new StringTokenizer(line);  

String [] array = new String[st.countTokens()];

int i = 0;

while(i < array.length){

array[i++] = st.nextToken();

}

Student student = new Student(array[0].trim(), array[1].trim(),

Integer.parseInt(array[2].trim()), Integer.parseInt(array[3].trim()),

Integer.parseInt(array[4].trim()), Integer.parseInt(array[5].trim()));

this.vector.addElement(student);

}

}catch(FileNotFoundException ex){

JOptionPane.showMessageDialog(this.f, "선택하신 파일을 찾을 수 없습니다.", 

"File Not Found", JOptionPane.ERROR_MESSAGE);

}catch(NoSuchElementException ex){}

JOptionPane.showMessageDialog(this.f,

this.vector.size() + "명의 학생이 잘 처리됐습니다.", 

"Success", JOptionPane.INFORMATION_MESSAGE);

this.tab.setEnabledAt(2, true);

}

}






import java.awt.BorderLayout;

import java.awt.Font;

import java.awt.GridLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;

import javax.swing.border.TitledBorder;



public class InputPanel1 extends JPanel {

private Vector<Student> vector;

private JFrame f;

private JLabel lblHakbun, lblName, lblKor,lblEng, lblMat, lblEdp;

private JTextField tfHakbun, tfName, tfKor, tfEng, tfMat, tfEdp;

private JButton btnContinue, btnBreak;

private Font font;

private JTabbedPane tab;

public InputPanel1(Vector<Student> vector, JFrame f, JTabbedPane tab) {

this.vector = vector;

this.f = f;

this.tab = tab;

this.font = new Font("NanumGotic", Font.PLAIN, 20);

this.setLayout(new BorderLayout());

this.add("Center", getCenter());

this.add("South", getSouth());

}

private JPanel getSouth(){

JPanel p = new JPanel();

p.add(this.btnContinue = new JButton("입력하기"));

this.btnContinue.setFont(font);

this.btnContinue.addActionListener(

new InputAction1(this.vector, this.f, this.tab, this.tfHakbun, tfName, 

                     this.tfKor, this.tfEng, this.tfMat, this.tfEdp));

p.add(this.btnBreak = new JButton("출력하기"));

//if(this.vector.size() == 0) this.btnBreak.setEnabled(false);

this.btnBreak.setFont(font);

this.btnBreak.addActionListener(

new InputAction1(this.vector, this.f, this.tab, this.tfHakbun, tfName, 

                     this.tfKor, this.tfEng,this.tfMat, this.tfEdp));

return p;

}

private JPanel getCenter(){

JPanel p, inner;

inner = new JPanel();

inner.setBorder(new TitledBorder("성적데이터입력"));

inner.setLayout(new GridLayout(6,2,10,10));

inner.add(this.lblHakbun = new JLabel("학번"));

this.lblHakbun.setFont(font);

inner.add(this.tfHakbun = new JTextField(10));

this.tfHakbun.setFont(font);

inner.add(this.lblName = new JLabel("이름"));

this.lblName.setFont(font);

inner.add(this.tfName = new JTextField());

this.tfName.setFont(font);

inner.add(this.lblKor = new JLabel("국어"));

this.lblKor.setFont(font);

inner.add(this.tfKor = new JTextField());

this.tfKor.setFont(font);

inner.add(this.lblEng = new JLabel("영어"));

this.lblEng.setFont(font);

inner.add(this.tfEng = new JTextField());

this.tfEng.setFont(font);

inner.add(this.lblMat = new JLabel("수학"));

this.lblMat.setFont(font);

inner.add(this.tfMat = new JTextField());

this.tfMat.setFont(font);

inner.add(this.lblEdp = new JLabel("전산"));

this.lblEdp.setFont(font);

inner.add(this.tfEdp = new JTextField());

this.tfEdp.setFont(font);

p = new JPanel();

p.add(inner);

return p;

}

}








import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;


public class InputAction1 implements ActionListener {

private Vector<Student> vector;

private JFrame f;

private JTabbedPane tab;

private JTextField tfHakbun, tfName, tfKor, tfEng, tfMat, tfEdp;

public InputAction1(Vector<Student> vector, JFrame f, JTabbedPane tab,

JTextField tfHakbun, JTextField tfName, JTextField tfKor,

JTextField tfEng, JTextField tfMat, JTextField tfEdp) {

this.vector = vector;

this.f = f;

this.tab = tab;

this.tfHakbun = tfHakbun;

this.tfName = tfName;

this.tfKor = tfKor;

this.tfEng = tfEng;

this.tfMat = tfMat;

this.tfEdp = tfEdp;

}


@Override

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("입력하기")){

if(!this.check()){

JOptionPane.showMessageDialog(this.f, "입력되지 않은 데이터가 있습니다", 

"Warning", JOptionPane.WARNING_MESSAGE);

this.tfHakbun.requestFocus();

}else{

Student s = new Student(this.tfHakbun.getText().trim(), 

                                this.tfName.getText().trim(),

                                Integer.parseInt(this.tfKor.getText().trim()),

                                Integer.parseInt(this.tfEng.getText().trim()),

                                Integer.parseInt(this.tfMat.getText().trim()),

                                Integer.parseInt(this.tfEdp.getText().trim()));

this.vector.addElement(s);

JOptionPane.showMessageDialog(this.f, "입력됐습니다", 

"Success", JOptionPane.INFORMATION_MESSAGE);

this.tab.setEnabledAt(2, true);

this.tfHakbun.setText("");  this.tfName.setText("");

this.tfKor.setText("");  this.tfEng.setText("");

this.tfMat.setText("");  this.tfEdp.setText("");

}

}else if(e.getActionCommand().equals("출력하기")){

if(this.vector.size() == 0){

JOptionPane.showMessageDialog(this.f, "데이터가 없습니다.", 

"Error", JOptionPane.ERROR_MESSAGE);

this.tfHakbun.requestFocus();

return;

}

this.tab.setSelectedIndex(2);

}

}

private boolean check(){

if(this.tfHakbun.getText().length() == 0 || 

this.tfName.getText().length() == 0 ||

this.tfKor.getText().length() == 0 ||

this.tfEng.getText().length() == 0 ||

this.tfMat.getText().length() == 0 ||

this.tfEdp.getText().length() == 0) return false;

else return true;

}


}







import java.util.Vector;


public class Calc {

private Vector<Student> vector;


public Calc(Vector<Student> vector) {

this.vector = vector;

}

public void calc(){

for(int i = 0 ; i < this.vector.size() ; i++){

Student s = this.vector.get(i);

s.setTot(s.getKor() + s.getEng() + s.getMat() + s.getEdp());

s.setAvg(s.getTot() / 4.);

s.setGrade(this.getGrade(s.getAvg()));

}

}

private char getGrade(double avg){

if(avg <=100 && avg >= 90) return 'A';

else if(avg < 90 && avg >= 80) return 'B';

else if(avg < 80 && avg >= 70) return 'C';

else if(avg < 70 && avg >= 60) return 'D';

else return 'F';

}

}






import java.util.Vector;


public class Sort {

private Vector<Student> vector;


public Sort(Vector<Student> vector) {

this.vector = vector;

for(int i = 0 ; i < this.vector.size() ; i++)

this.vector.get(i).setRanking(1);

}

public void sort(){   //랭킹을 위한 선택정렬

for(int i = 0 ; i < this.vector.size() - 1 ; i++){

for(int j = i +1 ; j < this.vector.size() ; j++){

if(this.vector.get(i).compareTo(this.vector.get(j)) > 0){

this.vector.get(j).setRanking(this.vector.get(j).getRanking() + 1);

}else if(this.vector.get(i).compareTo(this.vector.get(j)) < 0){

this.vector.get(i).setRanking(this.vector.get(i).getRanking() +1);

}

}

}

}

}






import java.util.Vector;


import javax.swing.table.DefaultTableModel;


public class StudentModel extends DefaultTableModel {

private Vector<Student> vector;

private int choice;


public StudentModel(Vector<Student> vector, int choice) {

this.vector = vector;

this.choice = choice;

setModelData();

}

private void setModelData(){

Vector<String> columnVector = new Vector<String>(1,1);

String [] array = {"학번", "이름", "국어", "영어", "수학", "전산", "총점",

                  "평균", "학점", "등수"};

for(int i = 0 ; i < choice ; i++)  columnVector.addElement(array[i]);

Vector<Object> dataVector = new Vector<Object>(1,1);

for(int i = 0 ; i < this.vector.size() ; i++){

Vector<String> tempVector = new Vector<String>(1,1);

for(String str : this.vector.get(i).toArray())

tempVector.addElement(str);

tempVector.setSize(choice);

tempVector.trimToSize();

dataVector.addElement(tempVector);

}

this.setDataVector(dataVector, columnVector);

}

}






import java.awt.BorderLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;


public class OutputPanel extends JPanel{

private Vector<Student> vector;

private JFrame f;

private JScrollPane pane;

private JTable table;

private JButton btnOriginal, btnCalc, btnSort, btnDelete;

private JPanel p;

OutputPanel(Vector<Student> vector, JFrame f) {

this.vector = vector;

this.f = f;

this.p = new JPanel();

this.table = new JTable();

this.btnOriginal = new JButton("원본보기");

this.btnOriginal.addActionListener(new OutputAction(this.vector, this.f, this.table));

this.btnCalc = new JButton("계산하기");

this.btnCalc.addActionListener(new OutputAction(this.vector, this.f, this.table));

this.btnSort = new JButton("소팅하기");

this.btnSort.addActionListener(new OutputAction(this.vector, this.f, this.table));

this.btnDelete = new JButton("삭제하기");

this.btnDelete.addActionListener(new OutputAction(this.vector, this.f, this.table));

pane = new JScrollPane(this.table, 

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

this.setLayout(new BorderLayout());

this.add("Center", pane);

this.p.add(this.btnOriginal);  this.p.add(this.btnCalc);  this.p.add(this.btnSort);  

this.p.add(this.btnDelete);

this.add("North", p);

}

}







import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JTable;



public class OutputAction implements ActionListener {

private JFrame f;

private Vector<Student> vector;

private JTable table;

OutputAction(Vector<Student> vector, JFrame f, JTable table){

this.vector = vector;

this.f = f;

this.table = table;

}

@Override

public void actionPerformed(ActionEvent e) {

switch(e.getActionCommand()){

case "원본보기": viewOriginal(); break;

case "계산하기": calc(); break;

case "소팅하기": sort(); break;

case "삭제하기": delete(); break;

}

}

private void delete() {

int [] array = this.table.getSelectedRows(); //선택한 행을 array 배열에 넣음.

// for(int i = 0 ; i<array.length ; i++){

// Student s = this.vector.get(array[i]);

// this.vector.removeElement(s);

//앞에서부터 삭제하면 두개이상 지울 때, 삭제한 파일 다음 값이 앞으로 오게 되는데 다음 값을 지울 때 위치에대한 에러가 발생

for(int i = array.length-1 ; i>=0 ; i--){

this.vector.removeElementAt(array[i]);

}

this.sort();  //삭제된 것을 제외하고 다시 정렬.

}

private void viewOriginal(){

this.table.setModel(new StudentModel(this.vector, 6));

}

private void calc(){

Calc calc = new Calc(this.vector);

calc.calc();

this.table.setModel(new StudentModel(this.vector, 9));

}

private void sort(){

Sort sort = new Sort(this.vector);

sort.sort();

this.table.setModel(new StudentModel(this.vector, 10));

}


}






import java.awt.Container;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JTabbedPane;


public class Main {

private JFrame f;

private JTabbedPane tab;

private Container con;

private Vector<Student> vector;

private Main(){

this.f = new JFrame("성적관리프로그램 V2.0");

this.tab = new JTabbedPane();

this.con = this.f.getContentPane();

this.vector = new Vector<Student>(1,1);

}

private void display(){

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.f.setResizable(false);

this.tab.addTab("파일데이타입력", new InputPanel(this.vector, this.f, this.tab));

this.tab.addTab("일반데이타입력", new InputPanel1(this.vector, this.f, this.tab));

this.tab.addTab("데이터출력", new OutputPanel(this.vector, this.f));

this.tab.setEnabledAt(2, false);

this.con.add(this.tab);

this.f.setSize(500, 400);

this.f.setLocationRelativeTo(null);

this.f.setVisible(true);

}

public static void main(String[] args) {

new Main().display();

}

}






ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

===================================================================

환자관리프로그램

1.


public class Person implements Comparable<Person>  {

private int num; // 번호

private String part; // 진찰부서

private int jcash; // 진찰비

private int icash; // 입원비

private double tot; // 진료비

private int day; // 입원일

private int age; // 나이

public String [] toArray(){

String [] array = new String[5];

array[0] = String.valueOf(this.num);   

array[1] = this.part;

array[2] = String.valueOf(this.jcash);       

array[3] = String.valueOf(this.icash);     

array[4] = String.valueOf((int)this.tot);       

return array;

}

@Override

public int compareTo(Person p){

return (int)(this.getTot() - p.getTot());

}

public int getNum() {

return num;

}

public void setNum(int num) {

this.num = num;

}

public String getPart() {

return part;

}

public void setPart(String part) {

this.part = part;

}

public int getJcash() {

return jcash;

}

public void setJcash(int jcash) {

this.jcash = jcash;

}

public int getIcash() {

return icash;

}

public void setIcash(int icash) {

this.icash = icash;

}

public double getTot() {

return tot;

}

public void setTot(double tot) {

this.tot = tot;

}

public int getDay() {

return day;

}

public void setDay(int day) {

this.day = day;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}


}





import java.awt.BorderLayout;

import java.awt.Font;

import java.awt.GridLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;

import javax.swing.border.TitledBorder;



public class Input extends JPanel {

private Vector<Person> vector;

private JFrame f;

private JLabel lblNumber, lblCode, lblDays,lblAge;

private JTextField tfNumber, tfCode, tfDays, tfAge;

private JButton btnAdd;

private Font font;

private JTabbedPane tab;

public Input(Vector<Person> vector, JFrame f, JTabbedPane tab) {

this.vector = vector;

this.f = f;

this.tab = tab;

this.font = new Font("NanumGotic", Font.PLAIN, 20);

this.setLayout(new BorderLayout());

this.add("Center", getCenter());

this.add("South", getSouth());

}

private JPanel getSouth(){

JPanel p = new JPanel();

p.add(this.btnAdd = new JButton("Add"));

this.btnAdd.setFont(font);

this.btnAdd.addActionListener(

new InputAction1(this.vector, this.f, this.tab, this.tfNumber, tfCode, 

                     this.tfDays, this.tfAge));

return p;

}

private JPanel getCenter(){

JPanel p, inner;

inner = new JPanel();

inner.setBorder(new TitledBorder("Data Input"));

inner.setLayout(new GridLayout(4,2,10,10));

inner.add(this.lblNumber = new JLabel("Number :"));

this.lblNumber.setFont(font);

inner.add(this.tfNumber = new JTextField(10));

this.tfNumber.setFont(font);

inner.add(this.lblCode = new JLabel("Code :"));

this.lblCode.setFont(font);

inner.add(this.tfCode = new JTextField());

this.tfCode.setFont(font);

inner.add(this.lblDays = new JLabel("Days :"));

this.lblDays.setFont(font);

inner.add(this.tfDays = new JTextField());

this.tfDays.setFont(font);

inner.add(this.lblAge = new JLabel("Age :"));

this.lblAge.setFont(font);

inner.add(this.tfAge = new JTextField());

this.tfAge.setFont(font);

/* inner.add(this.btnAdd = new JButton("Add"));

this.btnAdd.setFont(font);

this.btnAdd.addActionListener(new InputAction1(this.vector, this.f, this.tab, this.tfNumber, tfCode, this.tfDays, this.tfAge));

*/

p = new JPanel();

p.add(inner);

return p;

}

}







import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;


public class InputAction1 implements ActionListener {

private Vector<Person> vector;

private JFrame f;

private JTabbedPane tab;

private JTextField tfNumber, tfCode, tfDays, tfAge;

int count = 0;

public InputAction1(Vector<Person> vector, JFrame f, JTabbedPane tab,

JTextField tfNumber, JTextField tfCode, JTextField tfDays,

JTextField tfAge) {

this.vector = vector;

this.f = f;

this.tab = tab;

this.tfNumber = tfNumber;

this.tfCode = tfCode;

this.tfDays = tfDays;

this.tfAge = tfAge;

}


@Override

public void actionPerformed(ActionEvent e) {

String msg = null;

if(e.getActionCommand().equals("Add")){

if(count == 5){

JOptionPane.showMessageDialog(this.f, "더 이상 데이터를 입력할 수 없습니다.", 

"Warning", JOptionPane.WARNING_MESSAGE);

}

else{

if(!this.check()){

JOptionPane.showMessageDialog(this.f, "입력되지 않은 데이터가 있습니다", 

"Warning", JOptionPane.WARNING_MESSAGE);

this.tfNumber.requestFocus();

}else{

Person p = new Person();

p.setNum(Integer.parseInt(this.tfNumber.getText().trim())); 

String part = null;

switch(this.tfCode.getText().trim())

{

case "MI" : part = "외과"; break;

case "NI" : part = "내과"; break;

case "SI" : part = "피부과"; break;

case "TI" : part ="소아과"; break;

case "VI" : part = "산부인과"; break;

case "WI" : part = "비뇨기과"; break;

}

p.setPart(part);

p.setDay(Integer.parseInt(this.tfDays.getText().trim()));

p.setAge(Integer.parseInt(this.tfAge.getText().trim()));

this.vector.addElement(p);

count++;

if(count == 1) msg = "1st ";

else if(count == 2) msg = "2nd ";

else msg = count +"rd ";

JOptionPane.showMessageDialog(this.f, msg+"patients added successfully.", 

"Success", JOptionPane.INFORMATION_MESSAGE);

// this.tab.setEnabledAt(2, true);

this.tfNumber.setText("");  this.tfCode.setText("");

this.tfDays.setText("");  this.tfAge.setText("");

}

}

}

/* else if(e.getActionCommand().equals("출력하기")){

if(this.vector.size() == 0){

JOptionPane.showMessageDialog(this.f, "데이터가 없습니다.", 

"Error", JOptionPane.ERROR_MESSAGE);

this.tfNumber.requestFocus();

return;

}

this.tab.setSelectedIndex(2);

}

*/ }

private boolean check(){

if(this.tfNumber.getText().length() == 0 || 

this.tfCode.getText().length() == 0 ||

this.tfDays.getText().length() == 0 ||

this.tfAge.getText().length() == 0 ) return false;

else return true;

}


}







import java.util.Vector;



public class Calc {

private Vector<Person> vector;

Person person;

public Calc(Vector<Person> vector)

{

this.vector = vector;

}

void calc()

{

int num1 = 0;

double num2 = 0;

for(int i = 0; i <this.vector.size(); i++)

{

person = vector.get(i);

if(person.getDay() <= 3){ num1 = 30000; num2 = 1.00; }

else if(person.getDay() >= 10 && person.getDay() < 15) { num1 = 25000; num2 = 0.85; }

else if(person.getDay() >= 15 && person.getDay() < 20) { num1 = 25000; num2 = 0.80; }

else if(person.getDay() >= 20 && person.getDay() < 30) { num1 = 25000; num2 = 0.77; }

else if(person.getDay() >= 30 && person.getDay() < 100) { num1 = 25000; num2 = 0.72; }

else if(person.getDay() >= 100) { num1 = 25000; num2 = 0.68; }

person.setIcash((int)(person.getDay() * num1 * num2)); //입원비.....

if(person.getAge() < 10) person.setJcash(7000);

else if(person.getAge() >= 10 && person.getAge() < 20) person.setJcash(5000);

else if(person.getAge() >= 20 && person.getAge() < 30) person.setJcash(8000);

else if(person.getAge() >= 30 && person.getAge() < 40) person.setJcash(7000);

else if(person.getAge() >= 40 && person.getAge() < 50) person.setJcash(4500);

else if(person.getAge() >= 50) person.setJcash(2300);

person.setTot(person.getIcash() + person.getJcash()); //진료비......

}


}

}





import java.util.Vector;


public class Sort

{

private Vector<Person> vector;

Person temp = null;

public Sort(Vector<Person> vector)

{

this.vector = vector;

//for(int i = 0 ; i < this.vector.size() ; i++)

//this.vector.get(i).setRanking(1);

}

public void sort()

for(int i = 0 ; i < this.vector.size() - 1 ; i++){

for(int j = i + 1 ; j < this.vector.size() ; j++){

if(this.vector.get(i).compareTo(this.vector.get(j)) < 0)

{

this.temp = (Person)this.vector.get(i);

this.vector.set(i,this.vector.get(j));

this.vector.set(j, this.temp);

}

}

}

}

}





import java.awt.BorderLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;



public class OutputPanel extends JPanel {

private Vector<Person> vector;

private JFrame f;

private JTable table;

private JButton btnDisplay, btnPrint;

private JPanel p;

private JScrollPane pane;

OutputPanel(Vector<Person> vector, JFrame f){

this.vector = vector;

this.f = f;

this.table = new JTable();

this.p = new JPanel();

this.btnDisplay = new JButton("Display");

this.btnDisplay.addActionListener(new OutputAction(this.vector, this.f, this.table));

this.btnPrint = new JButton("Print");

this.btnPrint.addActionListener(new OutputAction(this.vector, this.f, this.table));


pane = new JScrollPane(this.table, 

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

this.setLayout(new BorderLayout());

this.add("Center", pane);

this.p.add(this.btnDisplay);  this.p.add(this.btnPrint);

this.add("North", p);

}

}






import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JTable;


public class OutputAction implements ActionListener {

private JFrame f;

private Vector<Person> vector;

private JTable table;


OutputAction(Vector<Person> vector, JFrame f, JTable table) {

this.vector = vector;

this.f = f;

this.table = table;

}


@Override

public void actionPerformed(ActionEvent e) {

switch (e.getActionCommand().trim())

{

case "Display" : viewDisplay();

break;

case "Print" :  viewPrint();

  break;

}


}


private void viewDisplay() {

if(vector.size()==0){

JOptionPane.showMessageDialog(this.f, "Patients Data empty", 

"Warning", JOptionPane.WARNING_MESSAGE);}

Calc calc = new Calc(this.vector);

calc.calc();

Sort sort = new Sort(this.vector);

sort.sort();

this.table.setModel(new PersonModel(this.vector));

}


private void viewPrint() {

System.out.println("                <<Hospital Management Program>>");

System.out.println("----------------------------------------------------------");

System.out.println("No    Department    Consulation Charge      Hospital Charge    SUM");

System.out.println("----------------------------------------------------------");

for(int i = 0; i< this.vector.size(); i ++){

Person person = vector.get(i);

System.out.println(person.getNum() + "\t" + person.getPart() + "\t" + person.getJcash()

+"\t" + person.getIcash() + "\t" + (int)person.getTot());

}

}


}





import java.util.Vector;


import javax.swing.table.DefaultTableModel;


public class PersonModel extends DefaultTableModel {

private Vector<Person> vector;


public PersonModel(Vector<Person> vector) {

this.vector = vector;

setModelData();

}


private void setModelData() {

Vector<String> columnVector = new Vector<String>(1, 1);

String[] array = { "No", "Department", "Consultation Charge",

"Hospital Charge", "SUM" };

for (int i = 0; i < array.length; i++)

columnVector.addElement(array[i]);


Vector<Object> dataVector = new Vector<Object>(1, 1);

for (int i = 0; i < this.vector.size(); i++) {

Vector<String> tempVector = new Vector<String>(1, 1);

for (String str : this.vector.get(i).toArray())

tempVector.addElement(str);

// tempVector.setSize(choice);

tempVector.trimToSize();

dataVector.addElement(tempVector);

}

this.setDataVector(dataVector, columnVector);

}

}






import java.awt.Container;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JTabbedPane;


public class Main {

private JFrame f;

private JTabbedPane tab;

private Container con;

private Vector<Person> vector;

private Main(){

this.f = new JFrame("Hospital Management Program");

this.tab = new JTabbedPane();

this.con = this.f.getContentPane();

this.vector = new Vector<Person>(1,1);

}

private void display(){

this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.f.setResizable(false);

this.tab.addTab("Input Data Panel", new Input(this.vector, this.f, this.tab));

this.tab.addTab("Display Data Panel", new OutputPanel(this.vector, this.f));

this.con.add(this.tab);

this.f.setSize(500, 400);

this.f.setLocationRelativeTo(null);

this.f.setVisible(true);

}

public static void main(String[] args) {

new Main().display();

}


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

2.v샘

public class Patients {

private String no;   

private String code;  

private int days;      

private int age;    

private String department;    

private int jinchalfee;           

private int ipwonfee;            

private int sum;                    

public Patients(String no, String code, int days, int age) {

this.no = no;     this.code = code;    

this.days = days;      this.age = age;

}

public String getDepartment() {

return department;

}

public void setDepartment(String department) {

this.department = department;

}

public int getJinchalfee() {

return jinchalfee;

}

public void setJinchalfee(int jinchalfee) {

this.jinchalfee = jinchalfee;

}

public int getIpwonfee() {

return ipwonfee;

}

public void setIpwonfee(int ipwonfee) {

this.ipwonfee = ipwonfee;

}

public int getSum() {

return sum;

}

public void setSum(int sum) {

this.sum = sum;

}

public String getNo() {

return no;

}

public String getCode() {

return code;

}

public int getDays() {

return days;

}

public int getAge() {

return age;

}

}







import java.awt.Container;

import java.awt.Font;

import java.awt.Toolkit;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JTabbedPane;


public class Main {

private JFrame f;

private JTabbedPane tab;

private Container con;

private Vector<Patients> vector;

private Font font;

private Main(){

this.vector = new Vector<Patients>(1,1);

this.font = new Font("NanumGothic", Font.BOLD, 25);

this.f = new JFrame("Hospital Management Program");

this.f.addWindowListener(new WindowControl(this.f));

this.con = f.getContentPane();

this.tab = new JTabbedPane();

}

private void display(){ 

this.tab.add(new LoginView(this.font, this.tab), "Login");

this.tab.add(new InputView(vector, this.font, this.tab), "Input Data Panel");

this.tab.add(new OutputView(vector), "Display Data Panel");

this.tab.setEnabledAt(0, true);

this.tab.setEnabledAt(1, false);

this.tab.setEnabledAt(2, false);

this.con.add(this.tab, "Center");

this.f.setSize(800,600);

this.f.setLocationRelativeTo(null);

this.f.setVisible(true);

}

public static void main(String[] args) {

new Main().display();

}

}







import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import javax.swing.JOptionPane;


class WindowControl extends WindowAdapter {

private JFrame f;

WindowControl(JFrame f){

this.f = f;

}

public void windowClosing(WindowEvent evt){

int result = JOptionPane.showConfirmDialog(f, "정말 종료하시겠습니까 ? ","Window Close", JOptionPane.YES_NO_OPTION);

if(result == JOptionPane.YES_OPTION) {

System.exit(0);

}else{

f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

}

}

}







import java.awt.BorderLayout;

import java.awt.Canvas;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.GridLayout;

import java.awt.Image;

import java.awt.Toolkit;


import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;

import javax.swing.border.BevelBorder;

import javax.swing.border.TitledBorder;



public class LoginView extends JPanel {

private Font font;

private JTabbedPane tab;

private JPanel p, pLogin, pCenter, pWest, pSouth;

private JLabel labelID,labelPwd;

private JTextField tfID;

private JPasswordField tfPwd;

private JButton btnOk, btnCancel;

private MyCanvas mc;

LoginView(Font font, JTabbedPane tab) {

this.font = font;

this.tab = tab;

p = new JPanel();

pCenter = new JPanel();

pLogin = new JPanel();

pWest = new JPanel();

pSouth = new JPanel();

mc = new MyCanvas();

initComponent();

}

private void initComponent(){

p.setLayout(new BorderLayout());

p.add(mc, "Center");

pLogin.setLayout(new BorderLayout());

pLogin.setBorder(new TitledBorder(

                new BevelBorder(BevelBorder.RAISED), "Login",

                TitledBorder.DEFAULT_JUSTIFICATION,

                TitledBorder.DEFAULT_POSITION, this.font, Color.RED));

pCenter.setLayout(new GridLayout(2,1,10,10));

pCenter.add(tfID = new JTextField(10));

tfID.setFont(this.font);

pCenter.add(tfPwd = new JPasswordField(10));

tfPwd.setFont(this.font);

pWest.setLayout(new GridLayout(2,1,10,10));

pWest.add(labelID = new JLabel("아이디 : "));

labelID.setFont(this.font);

pWest.add(labelPwd = new JLabel("패스워드 : "));

labelPwd.setFont(this.font);

pSouth.add(btnOk = new JButton("OK"));

btnOk.setFont(this.font);

btnOk.addActionListener(new LoginActionController(this, this.tfID, this.tfPwd, this.tab));

pSouth.add(btnCancel = new JButton("Cancel"));

btnCancel.addActionListener(new LoginActionController(this, this.tfID, this.tfPwd, this.tab));

btnCancel.setFont(this.font);

pLogin.add("West",pWest);

pLogin.add("Center", pCenter);

pLogin.add("South", pSouth);

p.add(pLogin, "South");

add(p);

}

private class MyCanvas extends Canvas{

private Image img;

MyCanvas(){

img = Toolkit.getDefaultToolkit().getImage("images/hospital.gif");

this.setSize(300,350);

}

@Override

public void paint(Graphics g){

g.drawImage(img, p.getWidth() / 2 - this.img.getWidth(this) / 2, 

p.getHeight() / 2 - this.img.getHeight(this) / 2, this.img.getWidth(this), this.img.getHeight(this), this);

}

}

}






import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;



public class LoginActionController implements ActionListener {

private JPanel p;

private JTextField tfID;

private JPasswordField tfPwd;

private JTabbedPane pane;

private final String strID = "javasoft";

private final String strPwd = "123456";

LoginActionController(JPanel p,JTextField tfID, JPasswordField tfPwd, JTabbedPane pane){

this.p = p;

this.tfID = tfID;

this.tfPwd = tfPwd;

this.pane = pane;

}

@Override

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("OK")){

if(this.tfID.getText().trim().equals(this.strID) &&

this.tfPwd.getText().trim().equals(this.strPwd)){

JOptionPane.showMessageDialog(this.p, this.strID + "님! 환영합니다.", "Success",

JOptionPane.INFORMATION_MESSAGE);

this.pane.setEnabledAt(1, true);

this.pane.setSelectedIndex(1);

}else{

JOptionPane.showMessageDialog(this.p, "아이디 혹은 패스워드가 일치하지 않습니다.", "Failure",

JOptionPane.WARNING_MESSAGE);

this.pane.transferFocus();

}

}else{

JOptionPane.showMessageDialog(this.p, "로그인해 주십시오.", "Warning",

JOptionPane.WARNING_MESSAGE);

this.tfID.requestFocus();

}

}


}







import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Font;

import java.awt.GridLayout;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;

import javax.swing.border.BevelBorder;

import javax.swing.border.TitledBorder;


class InputView extends JPanel {

private Vector<Patients> vector;

private JPanel panel, pSouth, pCenter, pWest;

private JButton btnAdd;

private JComboBox<String> cbCode;

private JTextField tfNo, tfDays, tfAge;

private JLabel labelNo, labelCode, labelDays, labelAge;

private Font font;

private PatientsAddController addAction;

private JTabbedPane pane;

InputView(Vector<Patients> vector, Font font, JTabbedPane pane){

this.vector = vector;

this.font = font;

this.pane = pane;

panel = new JPanel();  

pSouth = new JPanel();    

pCenter = new JPanel();   

pWest = new JPanel();     

initComponent();

}

private void initComponent(){

panel.setLayout(new BorderLayout());

panel.setBorder(new TitledBorder(

                   new BevelBorder(BevelBorder.RAISED), "Data Input",

                   TitledBorder.DEFAULT_JUSTIFICATION,

                   TitledBorder.DEFAULT_POSITION, this.font, Color.RED));

pSouth.add(btnAdd = new JButton("Add"));

btnAdd.setFont(font);

btnAdd.setBorder(new BevelBorder(BevelBorder.RAISED));

pCenter.setLayout(new GridLayout(4,1,10,10));

tfNo = new JTextField(15);   tfNo.setFont(font);

String [] array = {"--Code--", "MI", "NI", "SI","TI", "VI", "WI"};

cbCode = new JComboBox<String>(array);

cbCode.setFont(font);

tfDays = new JTextField(15);  tfDays.setFont(font);

tfAge = new JTextField(15);  tfAge.setFont(font);

pCenter.add(tfNo);  pCenter.add(cbCode);

pCenter.add(tfDays);  pCenter.add(tfAge);

pWest.setLayout(new GridLayout(4,1,10,10));

labelNo = new JLabel("Number : ", JLabel.RIGHT);    

labelNo.setFont(font);

labelCode = new JLabel("Code : ", JLabel.RIGHT);   

labelCode.setFont(font);

labelDays = new JLabel("Days : ", JLabel.RIGHT);   

labelDays.setFont(font);

labelAge = new JLabel("Age : ", JLabel.RIGHT);     

labelAge.setFont(font);

pWest.add(labelNo);   pWest.add(labelCode);

pWest.add(labelDays);  pWest.add(labelAge);

panel.add("South", pSouth);

panel.add("West", pWest);

panel.add("Center", pCenter);

addAction = new PatientsAddController(this.vector, this, this.pane,

                                      tfNo, cbCode, tfDays, tfAge);

btnAdd.addActionListener(addAction);

add(panel);

}

}







import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JComboBox;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTabbedPane;

import javax.swing.JTextField;


class PatientsAddController implements ActionListener {

private Vector<Patients> vector;

private JPanel panel;

private JComboBox<String> cbCode;

private JTextField tfNo, tfDays, tfAge;

private JTabbedPane pane;

PatientsAddController(Vector<Patients> vector, JPanel panel, JTabbedPane pane,

                             JTextField tfNo, JComboBox<String> cbCode, 

                             JTextField tfDays, JTextField tfAge){

this.vector = vector;    this.panel = panel;

this.pane = pane;

this.tfNo = tfNo;           this.cbCode = cbCode;

this.tfDays = tfDays;     this.tfAge = tfAge;

}

@Override

public void actionPerformed(ActionEvent e) {

try{

checkData();

Patients p = new Patients(this.tfNo.getText().trim(),

                    this.cbCode.getSelectedItem().toString(),

                     Integer.parseInt(this.tfDays.getText().trim()),

                     Integer.parseInt(this.tfAge.getText().trim()));

this.tfNo.setText("");  

this.cbCode.setSelectedIndex(0);

this.tfDays.setText("");

this.tfAge.setText("");

this.vector.addElement(p);

new PatientsCalc(p);        

new PatientsSort(this.vector);

JOptionPane.showMessageDialog(this.panel, 

                                this.vector.size() + "th patients added successfully",

                                "Message",

                                JOptionPane.INFORMATION_MESSAGE);

this.pane.setEnabledAt(2, true);

}catch(PatientException ex){

JOptionPane.showMessageDialog(this.panel, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);

this.cbCode.transferFocusBackward();

}

}

private void checkData() throws PatientException{

if(this.tfNo.getText().trim().length() > 0 &&

this.cbCode.getSelectedIndex() > 0 &&

this.tfDays.getText().trim().length() > 0 &&

this.tfAge.getText().trim().length() > 0) return;

else throw new PatientException("모든 데이터는 필수 입력입니다.");

}

}






class PatientsCalc {

private Patients p;   //ȯ���Ѹ? ���

PatientsCalc(Patients p){

this.p = p;

calc();

}

private void calc(){

String code = this.p.getCode();

p.setDepartment(Util.getDepartment(code));  

int defaultIpwonFee = 0;   

int days = this.p.getDays();  

if(days <= 3) defaultIpwonFee = 30000;

else defaultIpwonFee = 25000;

int totalIpwonFee = defaultIpwonFee * days;  

double rate = Util.getRate(days);  

int ipwonFee = (int)(totalIpwonFee * rate);   

p.setIpwonfee(ipwonFee);

int jinchalFee = Util.getJinchalFee(p.getAge());  

p.setJinchalfee(jinchalFee);

int sum = jinchalFee + ipwonFee;  

p.setSum(sum);

}

}







//Utility Class

public class Util {

public static String getDepartment(String code){

String department = null;

switch(code){

case "MI" : department = "외과"; break;

case "NI" : department = "내과"; break;

case "SI" : department = "피부과"; break;

case "TI" : department = "소아과"; break;

case "VI" : department = "산부인과"; break;

case "WI" : department = "비뇨기과"; break;

}

return department;

}

public static int getJinchalFee(int age){

int jinchalfee = 0;

switch(age / 10){

case 0 : jinchalfee = 7000; break;

case 1 : jinchalfee = 5000; break;

case 2 : jinchalfee = 8000; break;

case 3 : jinchalfee = 7000; break;

case 4 : jinchalfee = 4500; break;

default : jinchalfee = 2300; 

}

return jinchalfee;

}

public static double getRate(int days){

double rate = 0.0;

if(days < 10) rate = 1.00;

else if(days >= 10 && days < 15) rate = 0.85;

else if(days >= 15 && days < 20) rate = 0.80;

else if(days >= 20 && days < 30) rate = 0.77;

else if(days >= 30 && days < 100) rate = 0.72;

else rate = 0.68;

return rate;

}

}






import java.util.Vector;


public class PatientsSort {

private Vector<Patients> vector;


PatientsSort(Vector<Patients> vector) {

this.vector = vector;

insertionSort();

}

private void insertionSort(){

int i, j;

Patients temp;

for(i = 1 ; i < this.vector.size() ; i++){

temp = this.vector.get(i);

for(j = i - 1 ; j >= 0 && this.vector.get(j).getSum() < temp.getSum() ; j--){

this.vector.set(j+1, this.vector.get(j));

}

this.vector.set(j + 1, temp);

}

}

}








@SuppressWarnings("serial")

public class PatientException extends Exception {

public PatientException(String msg){

super(msg);

}

}





import javax.swing.JPanel;

import javax.swing.JButton;

import javax.swing.JTable;

import javax.swing.JScrollPane;

import java.awt.BorderLayout;

import java.util.Vector;

import java.awt.Font;


public class OutputView extends JPanel {

private Vector<Patients> vector;

private JPanel panel;

private JButton btnDisplay, btnPrint;

private JTable table;

private JScrollPane pane;

private PrintController print;

private DisplayAction display;

public OutputView(Vector<Patients> vector){

this.setLayout(new BorderLayout());

this.vector = vector;

panel = new JPanel();   

btnDisplay = new JButton("Display");

btnPrint = new JButton("Print");

panel.add(btnDisplay);        panel.add(btnPrint);

table = new JTable();

table.setRowHeight(40);

table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

table.setFont(new Font("NanumGothic", Font.PLAIN, 25));

pane = new JScrollPane(table);

print = new PrintController(this.vector);

btnPrint.addActionListener(print);

display = new DisplayAction(this.vector, this, table);

btnDisplay.addActionListener(display);

this.add("North", panel);

this.add("Center", pane);

}

}






import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


public class PrintController implements ActionListener {

private Vector<Patients> vector;

public PrintController(Vector<Patients> vector){

this.vector = vector;

}

@Override

public void actionPerformed(ActionEvent e) {

printLabel();

if(this.vector.size() == 0){

System.out.println("                  현재 입력된 환자 데이터가 없습니다.");

return;

}

for(int i = 0 ; i < this.vector.size() ; i++){

Patients p = this.vector.get(i);

System.out.printf("%2s%13s%,20d%,20d%,20d\n",

                    p.getNo(), p.getDepartment(),

                    p.getJinchalfee(), p.getIpwonfee(),

                    p.getSum());

}

}

private void printLabel(){

System.out.println("\n                            <<Hospital Management Program>>");

System.out.println("-------------------------------------------------------------------------------");

System.out.println("No     Department        Consultation Charge     Hospital Charge      SUM");

System.out.println("-------------------------------------------------------------------------------");

}


}






import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;

import javax.swing.JPanel;

import javax.swing.JOptionPane;

import javax.swing.JTable;


public class DisplayAction implements ActionListener {

private Vector<Patients> vector;

private JPanel panel;

private JTable table;

public DisplayAction(Vector<Patients> vector, JPanel panel, JTable table){

this.vector = vector;

this.panel = panel;

this.table = table;

}

@Override

public void actionPerformed(ActionEvent e) {

if(this.vector.size() == 0){

JOptionPane.showMessageDialog(this.panel, 

                              "Patients Data is empty.", "Warning",

                              JOptionPane.WARNING_MESSAGE);

return;

}

this.table.setModel(new PatientsModel(this.vector));

}

}








import java.util.Vector;

import javax.swing.table.DefaultTableModel;


public class PatientsModel extends DefaultTableModel{

private Vector<Patients> vector;

public PatientsModel(Vector<Patients> vector){

this.vector = vector;

dataAddToTable();

}

private void dataAddToTable(){

String [] columnArray = {"No", "Department", "Consultation Charge", "Hospital Charge", "SUM"};

Vector<String> colVector = new Vector<String>(1,1);

for(String str : columnArray) colVector.addElement(str);

Vector<Object> dataVector = new Vector<Object>(1,1);

for(int i = 0 ; i < this.vector.size(); i++){

Patients p = this.vector.get(i);

Vector<String> row = new Vector<String>(1,1);

row.addElement(p.getNo());

row.addElement(p.getDepartment());

row.addElement(String.format("%,d", p.getJinchalfee()));

row.addElement(String.format("%,d", p.getIpwonfee()));

row.addElement(String.format("%,d",p.getSum()));

dataVector.addElement(row);

}

this.setDataVector(dataVector, colVector);

}

}






import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Vector;


import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTabbedPane;



class PatientOutputController implements ActionListener {

private JPanel panel;

private JTabbedPane pane;

private Vector<Patients> vector;

PatientOutputController(JPanel panel, JTabbedPane pane, Vector<Patients> vector){

this.panel = panel;

this.pane = pane;

this.vector = vector;

}

@Override

public void actionPerformed(ActionEvent e) {

if(this.vector.size() > 0) this.pane.setSelectedIndex(2);

else {

JOptionPane.showMessageDialog(this.panel, "�Էµ� �����Ͱ� ����ϴ�", "Error", 

JOptionPane.ERROR_MESSAGE);

this.pane.transferFocus();

}

}


}





=======================================================================

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

JavaSoft 회사 상품별판매 이익금 및 이익율표 작성하기 위한 프로그램

제품관리프로그램 (파일 입력, 로드, 계산, 파일출력)

public class Product {

private String name;

private int su;

private int saleprice;

private int buyprice;

private int fee;

private int salemoney;   //판매금액

private int buymoney;   //매입금액

private int money;   //이익금

private double rate;   //이익율

public Product(String name, int su, int saleprice, int buyprice, int fee) {

this.name = name;

this.su = su;

this.saleprice = saleprice;

this.buyprice = buyprice;

this.fee = fee;

}

@Override

public String toString(){

return String.format("%-15s%,10d%,10d%,10d%,10d%,20d%10.2f",

this.name, this.su, this.saleprice, this.buyprice, this.fee, this.money, this.rate);

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getSu() {

return su;

}

public void setSu(int su) {

this.su = su;

}

public int getSaleprice() {

return saleprice;

}

public void setSaleprice(int saleprice) {

this.saleprice = saleprice;

}

public int getBuyprice() {

return buyprice;

}

public void setBuyprice(int buyprice) {

this.buyprice = buyprice;

}

public int getFee() {

return fee;

}

public void setFee(int fee) {

this.fee = fee;

}

public int getSalemoney() {

return salemoney;

}

public void setSalemoney(int salemoney) {

this.salemoney = salemoney;

}

public int getBuymoney() {

return buymoney;

}

public void setBuymoney(int buymoney) {

this.buymoney = buymoney;

}

public int getMoney() {

return money;

}

public void setMoney(int money) {

this.money = money;

}

public double getRate() {

return rate;

}

public void setRate(double rate) {

this.rate = rate;

}

}






import java.util.Vector;


import javax.swing.JFrame;



public class Main {

private Vector<Product> vector;

private ProductView pv;

private Main(){

this.vector = new Vector<Product>(1,1);

this.pv = new ProductView(this.vector);

this.pv.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

this.pv.addWindowListener(new WindowController(this.pv));

}

private void display(){

this.pv.setTitle("제품관리프로그램");

this.pv.setSize(600, 400);

this.pv.setLocationRelativeTo(null);

this.pv.setVisible(true);

}

public static void main(String[] args) {

new Main().display();

}

}






import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;


import javax.swing.JOptionPane;


public class WindowController extends WindowAdapter {

private ProductView pv;

public WindowController(ProductView pv){

this.pv = pv;

}

@Override

public void windowClosing(WindowEvent evt){

int choice = JOptionPane.showConfirmDialog(this.pv, 

                                                    "정말 종료하시겠습니까?", "Question", 

                                                    JOptionPane.YES_NO_OPTION, 

                                                    JOptionPane.QUESTION_MESSAGE);

if(choice == JOptionPane.YES_OPTION){

System.exit(0);

}

}

}







import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Container;

import java.awt.Font;

import java.util.Vector;


import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.JTextField;

import javax.swing.border.BevelBorder;

import javax.swing.border.TitledBorder;


public class ProductView extends JFrame {

private Vector<Product> vector;

private JScrollPane pane;

private JTable table;

private JPanel pNorth;

private JLabel label;

private JTextField tf;

private JButton btnOpen, btnLoad, btnCalc, btnSave;

private Font font;

private Container con;

public ProductView(Vector<Product> vector) {

this.con = this.getContentPane();

this.con.setLayout(new BorderLayout());

this.vector = vector;

this.table = new JTable();

this.font = new Font("Loma", Font.PLAIN, 15);

this.pane = new JScrollPane(this.table, 

  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

                 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

this.pNorth = getNorth();

this.con.add("North", this.pNorth);

this.con.add("Center", this.pane);

}

private JPanel getNorth(){

JPanel p = new JPanel();

JPanel pInner = new JPanel();

pInner.setBorder(new TitledBorder(

new BevelBorder(BevelBorder.RAISED), 

"파일경로", TitledBorder.DEFAULT_JUSTIFICATION, 

TitledBorder.TOP, new Font("NanumGothic", Font.BOLD, 20), 

Color.RED));

pInner.add(this.label = new JLabel("Source : ", JLabel.RIGHT));

this.label.setFont(this.font);

pInner.add(this.tf = new JTextField(18));

this.tf.setFont(font);

this.tf.setEditable(false);

pInner.add(this.btnOpen = new JButton( 

new ImageIcon("images/open.gif")));

this.btnOpen.setToolTipText("파일열기");   //마우스에 대면 설명이 올라오는 기능.

this.btnOpen.addActionListener(new ProductActionController(this, this.table, this.tf,   

this.vector, 1));  //무엇이 눌렸는지 ProductionAction이 알게 하기 위해서, 식별자를 써줌. 1이 눌르면 파일열기~

pInner.add(this.btnLoad = new JButton(

new ImageIcon("images/load.gif")));

this.btnLoad.setToolTipText("데이터로드하기");

this.btnLoad.addActionListener(new ProductActionController(this, this.table, this.tf, 

this.vector, 2));

pInner.add(this.btnCalc = new JButton(

new ImageIcon("images/calc.gif")));

this.btnCalc.setToolTipText("계산하기");

this.btnCalc.addActionListener(new ProductActionController(this, this.table, this.tf, 

this.vector, 3));

pInner.add(this.btnSave = new JButton(

new ImageIcon("images/save.gif")));

this.btnSave.setToolTipText("파일로 저장하기");

this.btnSave.addActionListener(new ProductActionController(this, this.table, this.tf, 

this.vector, 4));

p.add(pInner);

return p;

}

}






import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.FileNotFoundException;

import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JTable;

import javax.swing.JTextField;



public class ProductActionController implements ActionListener {

private JFrame f;

private JTable table;

private Vector<Product> vector;

private JTextField tf;

private int choice;

public ProductActionController(JFrame f, JTable table, JTextField tf,

Vector<Product> vector, int choice) {

this.f = f;

this.table = table;

this.tf = tf;

this.vector = vector;

this.choice = choice;

}

@Override

public void actionPerformed(ActionEvent e) {

switch(this.choice){

case 1 : new OpenAction(this.f, this.tf);  break;

case 2 : 

try{

new LoadAction(this.tf, this.table, this.vector);  break;

}catch(FileNotFoundException ex){

JOptionPane.showMessageDialog(this.f, ex.getMessage());

}

break;

case 3 : new CalcAction(this.f, this.table, this.vector);  break;

case 4 : new SaveAction(this.f, this.vector);  break;  //다이얼로그를 띄어야 하니 프레임, 내보낼 벡터

}

}

}









import java.io.File;


import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JTextField;


public class OpenAction {

private JTextField tf;

private JFrame f;

OpenAction(JFrame f, JTextField tf){

this.f = f;

this.tf = tf;

this.open();

}

private void open(){

JFileChooser jc = new JFileChooser(".");

int choice = jc.showOpenDialog(this.f);

if(choice == JFileChooser.APPROVE_OPTION){  //확인버튼을 눌렀다면

File file = jc.getSelectedFile();

this.tf.setText(file.getAbsolutePath());

}

}

}







import java.io.FileNotFoundException;

import java.util.Vector;


import javax.swing.JTable;

import javax.swing.JTextField;



public class LoadAction {

private JTextField tf;

private JTable table;

private Vector<Product> vector;

LoadAction(JTextField tf, JTable table, Vector<Product> vector) throws FileNotFoundException{

this.tf = tf;

this.table = table;

this.vector = vector;

setData();

}

private void setData() throws FileNotFoundException{

this.table.setModel(new ProductModel(this.tf, this.vector));

}

}







import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

import java.util.Vector;


import javax.swing.JTextField;

import javax.swing.table.DefaultTableModel;



public class ProductModel extends DefaultTableModel {

private JTextField tf;

private Vector<Product> vector;

ProductModel(JTextField tf, Vector<Product> vector) throws FileNotFoundException{

this.tf = tf;

this.vector = vector;

setData();

//assert (this.vector.size() == 7) : "Error";  //이런식으로 확인해봐도 되고.

setTable();

}

private void setTable(){

Vector<String> columeVector = new Vector<String>(1,1);

String [] array = {"상품명", "수량", "판매단가", "매입단가", "운송료"};

for(String str : array)   columeVector.addElement(str);

Vector<Object> dataVector = new Vector<Object>(1,1);

for(int i = 0 ; i < this.vector.size() ; i++){

Vector<String> temp = new Vector<String>(1,1);

temp.addElement(this.vector.get(i).getName());

temp.addElement("" + this.vector.get(i).getSu());  //정수를 스트링으로 방법2

temp.addElement(String.valueOf(this.vector.get(i).getSaleprice())); //정수를 스트링으로 방법2

temp.addElement(Utility.toString(this.vector.get(i).getSu()));  //Utility.java를 만들어 쉽게 포멧팅

temp.addElement(Utility.toString(this.vector.get(i).getFee()));

dataVector.addElement(temp);

}

this.setDataVector(dataVector, columeVector);

}

private void setData() throws FileNotFoundException{

File file = new File(this.tf.getText().trim());

Scanner scan = new Scanner(file);

String line = null;

try{

while((line = scan.nextLine()) != null){

String [] array = line.split("\\s+");

//String name, int su, int saleprice, int buyprice, int fee

Product p = new Product(array[0], 

Integer.parseInt(array[1]), Integer.parseInt(array[2]),

Integer.parseInt(array[3]), Integer.parseInt(array[4]));

this.vector.addElement(p);

}

}catch(java.util.NoSuchElementException ex){}  //그냥하면 한 줄이 더찍히기 때문에 이렇게 처리 해줌

}

}








public class Utility {  //포메팅이 필요한 애들은 호출.

public static String toString(int value){

return String.format("%,d", value);

}

public static String toString(double value){

return String.format("%.2f", value);

}

}







import java.util.Vector;


import javax.swing.JFrame;

import javax.swing.JTable;

import javax.swing.table.DefaultTableModel;


public class CalcAction {

private JFrame f;

private JTable table;

private Vector<Product> vector;

public CalcAction(JFrame f, JTable table, Vector<Product> vector) {

this.f = f;

this.table = table;

this.vector = vector;

calc();

this.setTable();

}

private void setTable(){

Vector<String> columeVector = new Vector<String>(1,1);

String [] array = {"상품명", "수량", "판매단가", "매입단가", "운송료", "이익금", "이익율"};

for(String str : array)   columeVector.addElement(str);

Vector<Object> dataVector = new Vector<Object>(1,1);

for(int i = 0 ; i < this.vector.size() ; i++){

Vector<String> temp = new Vector<String>(1,1);

temp.addElement(this.vector.get(i).getName());

temp.addElement("" + this.vector.get(i).getSu());  //정수를 스트링으로 방법2

temp.addElement(String.valueOf(this.vector.get(i).getSaleprice())); //정수를 스트링으로 방법2

temp.addElement(String.valueOf(this.vector.get(i).getBuyprice()));

temp.addElement(String.valueOf(this.vector.get(i).getFee()));

temp.addElement(String.valueOf(this.vector.get(i).getMoney()));

temp.addElement(String.valueOf(this.vector.get(i).getRate()));

temp.addElement(Utility.toString(this.vector.get(i).getMoney()));

temp.addElement(Utility.toString(this.vector.get(i).getRate()));

dataVector.addElement(temp);

}

//this.setDataVector(dataVector, columeVector);  //디폴트 테이블모델에 자식이 아니기 때문에 setDataVector를 그대로 쓸 순 없다.

this.table.setModel(new DefaultTableModel(dataVector, columeVector));

}

private void calc(){

for(int i = 0 ; i < this.vector.size(); i++){

Product p = this.vector.get(i);

//판매금액

int salemoney = p.getSu() * p.getSaleprice();

//매입금액

int buymoney = p.getSu() * p.getBuyprice();

//이익금

int money = salemoney - (buymoney + p.getFee());

//이익율

double rate = (double)money / buymoney * 100;

p.setSalemoney(salemoney);

p.setBuymoney(buymoney);

p.setMoney(money);

p.setRate(rate);

}

}

}







import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.util.Vector;


import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JOptionPane;


public class SaveAction {

private JFrame f;

private Vector<Product> vector;

public SaveAction(JFrame f, Vector<Product> vector) {

this.f = f;

this.vector = vector;

save();

}

private void save(){

File file = null;

BufferedWriter bw = null;

JFileChooser jc = new JFileChooser(".");

int choice = jc.showSaveDialog(this.f);

if(choice == JFileChooser.APPROVE_OPTION){    //저장을 눌렀다면

file = jc.getSelectedFile();

try{

bw = new BufferedWriter(new FileWriter(file));

//BufferedOutputStream은 이미지 사운드 내보낼 때, BufferedWriter은   파일처리를 할 때 쓰임

printLabel(bw);

for(int i = 0 ; i < this.vector.size() ; i++){

bw.write(this.vector.get(i).toString() + "\n");

}

bw.flush();

JOptionPane.showMessageDialog(this.f, file.getAbsolutePath() + " 에 성공적으로 저장됐습니다", "Success", 

         JOptionPane.INFORMATION_MESSAGE);

}catch(java.io.IOException ex){

JOptionPane.showMessageDialog(this.f, ex.getMessage(), "Error", 

         JOptionPane.ERROR_MESSAGE);

}finally{

try{

bw.close();

}catch(java.io.IOException ex){}

}

}

}

private void printLabel(BufferedWriter bw) throws java.io.IOException{  //writer는 없으면 만들고 있으면 덮어쓴다.

bw.write("                                <<상품별 판매 이익금 및 이익율표>>\n");

bw.write("=======================================================\n");

bw.write("상품명        수량       판매단가      매입단가      운송료      이익금      이익율\n");

bw.write("=======================================================\n");

bw.flush();

}

}




+ Recent posts