### : 목차 구분 기호
--- : 목차 내에 항목 구분 기호

목차
1. 이론 및 정보
2. 설정 및 그 밖에
3. 소스코드
4. 과제

###################################
1. 이론 및 정보
-----------------------------------
4. ByteStream - 기본 데이터 타입을 한번에 주고 받을 수 있게 도와주는 ByteStream
          1) FileInputStream, FileOutputStream
          2) DataInputStream, DataOutputStream
          3) RandomAccessFile - 임의로 접근 가능, 순서대로 가져오는 것이 아님
                         inputsteam과 outputstream을 상속 받지 않음
                         datainput, dataoutput 인터페이스를 구현함
                         seek() 메서드, 원하는 위치 직접 찾아감
                         저장시 기존의 방법과 다르게 만들어야함


5. CharacterStream

6. File 클래스

----------------------------------- 
Thread
1. 프로그램과 프로세스 차이
프로그램 : 만들어진 소프트웨어, 저장되어 있는 상태
프로세스 : 현재 실행중인 상태
두개는 똑같은 놈인데 상태에 따라 달라짐

Process - 프로세스 -> 멀티프로세스
Processor - CPU

프로세스 안에서 하나의 작업단위는 Thread
Single Thread , Multi Thread

2. 모든 프로그램은 반드시 기본적으로 한개의 스래드를 가지고 있다. - main() 

3. 처리방식 - 똑같은 효과, 똑같은 결과
          1) Thread 클래스 - 쉬움
          2) Runnable 인터페이스 - 어려움
                    - 이미 다른 클래스를 상속 받았을 때 Thread를 상속 받을 수 없으니까 사용!


Thread의 LifeCycle

main은 부모스레드, 나머지는 자식 스레드, 여기서 부모 자식은 상속 관계가 아님
----------------------------------- 
java 5.0 새로 추가된 문법 Annotation
@Override
Annotation은 해당 기능이 제대로 설계되었는지
확인해줌, 예를 들어 @Override는 부모의 메서드를
똑같이 만들었는지 확인해서 알려줌
----------------------------------- 
----------------------------------- 
###################################
2. 설정 및 그 밖에
-----------------------------------
----------------------------------- 
###################################
3. 소스코드
-----------------------------------
3-1
/day13/src/io/bytestream/DataTest.java

package io.bytestream;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class DataTest {
    public static void main(String[] args) throws IOException {
        // TODO DataInputStream과 DataOutputStream
        FileOutputStream fout = new FileOutputStream("F:\\study\\dataTest.txt");
 
        //#1 숫자, 실수를 저장할 것임 4byte, 8byte 데이터는 어떻게 전달?
        //#1 FileOutputStream을 DataOutputStream으로 포장함, 확장해서 쓰겠끔
        DataOutputStream dout = new DataOutputStream(fout);
        
        dout.writeChar('가');
        dout.writeDouble(3.14);
        dout.writeInt(100);
        dout.writeBoolean(true);        
        dout.close();
        fout.close();
        
        //#2 읽어 오는 과정
        //#2 반드시 저장한 순서대로 읽어야함
        FileInputStream fin = new FileInputStream("F:\\study\\dataTest.txt");
        DataInputStream din = new DataInputStream(fin);
        System.out.println(din.readChar());
        System.out.println(din.readDouble());
        System.out.println(din.readInt());
        System.out.println(din.readBoolean());
        fin.close();
        din.close();
    }
}

----------------------------------- 
3-2
/day13/src/io/bytestream/RandomAccessFileTest.java

package io.bytestream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
    public static void main(String[] args) throws IOException {
        // TODO RandomAccessFile Test
        int[] data = { 102030405060708090100 };
        RandomAccessFile raf = new RandomAccessFile("F:\\study\\rafTest.txt""rw");
        for (int i = 0; i < data.length; i++) {
            raf.writeInt(data[i]);
        }
        
        //#1 1byte씩 8개 이동
        raf.seek(8);
        System.out.println(raf.readInt());
        
        //#2 
        raf.seek(4*3);
        System.out.println(raf.readInt());
    }
}

----------------------------------- 
3-3
/day13/src/io/charstream/CharTest1.java

package io.charstream;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class CharTest1 {
    static void streamTest(InputStream is) throws IOException{
        InputStreamReader isr = new InputStreamReader(is);         
        BufferedReader br = new BufferedReader(isr);
        //#1
        //int input = 0;
        
        //#2 null -> 빈 주소값을 참조, 어떤 인스턴스 주소를 참조하지 않음
        //#2 null -> 다양한 의미로 사용 가능함
        String input = null;
        while(true){
            //#1 
            //input = isr.read();
            
            //#2 string을 반환함
            input = br.readLine();
            
            //#1
            //if(-1 == input)
                
            //#2 null 더 이상 읽어들일 주소가 없다
            /*
            if(null == input)
                break;            
            */
            
            //#3 stop이라는 글자를 입력했을때 stop
            if(input.equals("stop"))
                break;        
            
            //#1
            //System.out.print((char)input);
            
            //#2
            System.out.println(input);
        }
        //#2 무줘건 닫아줘야함
        br.close();
        isr.close();
    }    
    public static void main(String[] args) throws IOException {
        // TODO 문자스트림 예제
        //#1 이 예제를 한글도 받을 수 있게 바꾸겠음
        //#1 어제 했떤 ByteTest2를 가지고 한글도 되고 다른 언어도 되도록
        //#1 문자스트림을 사용하여 가능하도록 만들겠음
        //#1 InputStreamReader  => ByteStream을 문자Stream으로 바꿔줌
        
        //#2 한글자씩이 아니라 한 줄씩 읽어서 처리 할 수 있는 방법은?
        //#2 InputStream는 이러한 기능을 가지지 못함
        //#2 readLine() 메서드를 사용해야함, 하지만 InputStream 가지고 있지 않음
        //#2 BufferedReader는 InputStreamReader를 도와주기 위한 FilterStream임
        streamTest(System.in);        
    }
}

----------------------------------- 
3-4
/day13/src/io/charstream/FileTest1.java

package io.charstream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileTest1 {
    public static void main(String[] args) throws IOException {
        // TODO 파일 처리 첫번째 예제
        //#1 어제한 FileTest1의 예제를 문자 스트림으로 바꿔 보자
        //#1 FileReader를 사용하면 문자 스트림으로 받을 수 있음
        //#1 eclipse에서는 한글이 안나옴
        //#2 #1은 초보자 코딩이라고 함, 좋은 코딩으로 바꿔보자
        BufferedReader br =  new BufferedReader(new FileReader("F:\\study\\test.txt"));
        
        //#1
        /*
        String input = null;
        while(true){
            input = br.readLine();
            if(input == null)
                break;
            System.out.println(input);
        }
        */
        
        //#2
        /*
        String input = br.readLine();
        while (input != null) {
            System.out.println(input);
            input = br.readLine();
        }
        */
        
        //#3 코드를 더 줄임
        String input;
        while ( (input = br.readLine()) != null)
            System.out.println(input);
        
        br.close();
    }
}

-----------------------------------  
3-5
/day13/src/io/charstream/FileTest2.java

package io.charstream;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileTest2 {
    public static void main(String[] args) throws IOException{
        // TODO 키보드로 부터 입력받아 파일로 출력
        //#1 bytestream을 문자스트림으로
        //#2 줄바꿈이 먹히지 않는다.
        //#3 코드를 리펙토링하고 끝나는 조건을 stop을 입력해서 종료
        //#4 do while문으로 변경
        FileWriter fout = new FileWriter("F:\\study\\test1.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = null;
        
        //#2
        /*    
        while(true){
            input = br.readLine();            
            if(null == input)
                break;
            
            //#2 줄바꿈 \n, 첫번째 위치 \r
            input+="\r\n";
            
            fout.write(input);
        }
        */
        
        //#3
        /*
        while(!(input = br.readLine()).equals("stop"))            
            fout.write(input+"\r\n");
        */
        
        //#4-1 
        /*
        input = br.readLine();
        do {
            fout.write(input+"\r\n");
        } while (!(input = br.readLine()).equals("stop"));
        */
        
        //#4-2
        do {
            if (input != null
                fout.write(input + "\r\n");
        } while (!(input = br.readLine()).equals("stop"));
        
        br.close();
        fout.close();        
    }
}
 
-----------------------------------
3-6
/day13/src/io/charstream/PrintWriterTest.java

package io.charstream;
import java.io.IOException;
import java.io.PrintWriter;
public class PrintWriterTest {
    public static void main(String[] args) throws IOException {
        // TODO PrintWriter 예제
        //#1 파일에 양식에 맞게 넣어서 하나의 데이터 형태로????
        //#1 예전에 한 성적표를 예제로 하겠음
        /*
        PrintWriter pw = new PrintWriter(
                new BufferedWriter(
                        new FileWriter("F:\\study\\sungjuk.txt")));
        */
        //#1 파일에 저장하기 위한 FileWriter, 
        //#1 FileWriter를 여러개를 저장하기 위한 BufferedWriter
        //#1 BufferedWriter를 포맷에 맞게 쓰기 위한 PrintWriter
        
        //#2 PrintWriter는 BufferedWriter, FileWriter 생략하게 해줄 수 있음
        PrintWriter pw = new PrintWriter("F:\\study\\sungjuk.txt");
        
        pw.println("**********성적표**********");
        pw.println("---------------------------------------------------------------------");
        pw.printf("%3s : %-5d %-5d %-5.1f %n""홍길동"9867, (float)((98+67)/2));
        pw.printf("%3s : %5d %5d %5.1f %n""임꺽정"8856, (float)((88+56)/2));
        pw.printf("%3s : %5d %5d %5.1f %n""신돌석"10097, (float)((100+97)/2));        
        pw.close();
    }
}





-----------------------------------  
3-7
/day13/src/io/bytestream/Employee.java

package io.bytestream;
import java.io.Serializable;
public class Employee implements Serializable{
    private int no;
    private String name;
    private String job;
    private int dept;
    private double point;
    public Employee(int no, String name, String job, int dept, double point) {
        super();
        this.no = no;
        this.name = name;
        this.job = job;
        this.dept = dept;
        this.point = point;
    }    
    @Override
    public String toString() {
        /*
        return "no=" + no + ", name=" + name + ", job=" + job
                + ", dept=" + dept + ", point=" + point;
        */
        return no + "\t" + name + "\t" + job
                + "\t" + dept + "\t\t" + point;
    }
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public int getDept() {
        return dept;
    }
    public void setDept(int dept) {
        this.dept = dept;
    }
    public double getPoint() {
        return point;
    }
    public void setPoint(double point) {
        this.point = point;
    }
}


/day13/src/io/bytestream/ObjectStreamTest.java

package io.bytestream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectStreamTest {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        // TODO ObjectInputStream, ObjectOutputStream
        //#1 데이터를 보관하기 위한 클래스를 설계 해보자 => 단순한 데이터가 아님
        //#1 반드시 데이터를 주고 받을 때에는 Byte로 나눠서 주고 받아짐
        //#1 복잡한 데이터를 주고 받기 위해서는(클래스를 이용해서 받을 때에는)
        //#1 반드시 Serializable 인터페이스를 상속 받아야 한다
        //#1 Serializable 는 복잡한 데이터를 한 줄로 세워서 보낸다, 단순화 시켜서
        //#1 받는 쪽에서도 한 줄로 받아서 복원을 시켜준다
        Employee[] emp = new Employee[3];
        emp[0= new Employee(1"홍길동""영업"11013.4);
        emp[1= new Employee(2"임꺽정""마케팅"11022.7);
        emp[2= new Employee(3"신돌석""총무"11033.8);
        
        ObjectOutputStream oos = 
                new ObjectOutputStream(
                        new FileOutputStream("F:\\study\\object.txt"));
        
        oos.writeObject(emp[0]);
        oos.writeObject(emp[1]);
        oos.writeObject(emp[2]);
        oos.close();
        
        System.out.println("**********사원정보**********");
        System.out.println("사번\t이름\t업무\t부서번호\t인사점수");
        //#1 불러다가 뿌려주는 것을 해봐라
        
        ObjectInputStream ois = 
                new ObjectInputStream(
                        new FileInputStream("F:\\study\\object.txt"));
        
        for (int i = 0; i < emp.length; i++) {
            Employee temp = (Employee) ois.readObject();
            // System.out.println(temp.getNo()+"\t"+temp.getName()+"\t"+temp.getJob()+"\t"+temp.getDept()+"\t\t"+temp.getPoint());
            System.out.println(temp);
        }
    }
}

----------------------------------- 
3-8
/day13/src/thread/ThreadTest1.java

package thread;
 
//#1
//class ThreadDemo1{
 
//#2 Thread를 상속받음
class ThreadDemo1 extends Thread{
    //#7
    //String name;
 
    public ThreadDemo1(String name) {
        //#7
        super(name);        
        
        //#1
        //this.name = name;
    }
 
    //#3 자식 쓰레드가 해야할 일을 적어주는 메서드
    @Override
    public void run() {
        int sum = 0;
        for (int i = 0; i < 5; i++) {
            //#6
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            sum += i;
            //#5
            //System.out.println(name + " : " + sum);//#5 name 추가
            
            //#7
            System.out.println(getName() + " : " + sum);            
            
            //#8
            //System.out.println(Thread.currentThread().getName() + " : " + sum);
        }
    }    
}
 
public class ThreadTest1 {
    public static void main(String[] args) {
        // TODO 첫번재 쓰레드 예제
        //#1 main에 현재 한개에 쓰래드가 생성될 것임
        ThreadDemo1 td1 = new ThreadDemo1("첫번째");
        
        //#2 Thread 2개 됨 , Thread 상속 받고 인스턴스 생성해서
        //#2 main + td1
        
        ThreadDemo1 td2 = new ThreadDemo1("두번째");//Thread + 1
        
        //#2 main은 부모스레드, 나머지는 자식 스레드
        
        //#3 현재 td1, td2는 아무일도 하지 않음
        
        //#4 실행시켜줘
        td1.start();
        td2.start();
        
        //#5 어떤 스레드인지 알고 싶음, 확인 해보자
        
        //#6 td1,td2가 서로 번갈아 가면서 할 수 있는 방법?
        
        //#7 이름을 따로 저장하지 않고 부모의 이름을 가져오는 방법
        //#7 부모 생성자에 이름을 받아서 getName()으로 가능
        
        //#8 만약 td1, td2에 생성자에 넣은 이름이 없다면?
    }
}

-----------------------------------  
3-9
/day13/src/thread/ThreadTest2.java

package thread;
 
class ThreadDemo2 implements Runnable{
    String name;
    public ThreadDemo2(String name) {
        this.name = name;
    }
    @Override
    public void run() {
        int sum = 0;
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sum += i;
            System.out.println(name + " : " + sum);
        }
    }    
}
 
public class ThreadTest2 {
    public static void main(String[] args) {
        // TODO 두번째 쓰레드 예제
        //#1 Runnable은 인스턴스 생성해도 Thread가 아님 아직 1개의 Thread
        ThreadDemo2 td1 = new ThreadDemo2("첫번째");
        ThreadDemo2 td2 = new ThreadDemo2("두번째");
        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);
        t1.start();
        t2.start();        
    }
}

----------------------------------- 
3-10
/day13/src/thread/ThreadTest3.java

package thread;
 
//#1
/*
class ThreadDemo3 extends Thread{
    @Override
    public void run() {
        System.out.println("자식 스레드 시작");
        int cnt = 0;
        do{
            try {
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("count : "+cnt);
            cnt++;
        }while(cnt < 10);
        System.out.println("자식 스레드 종료");
    }    
}
*/
 
//#2 runnable로 바꿔봐라
class ThreadDemo3 implements Runnable{
    @Override
    public void run() {
        System.out.println("자식 스레드 시작");
        int cnt = 0;
        do{
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("count : "+cnt);
            cnt++;
        }while(cnt < 10);
        System.out.println("자식 스레드 종료");
    }
}
 
public class ThreadTest3 {
    public static void main(String[] args) {
        // TODO 세번째 스레드 예제
        System.out.println("메인 스레드 시작");
        ThreadDemo3 td1 = new ThreadDemo3();
        Thread t1 = new Thread(td1);
        t1.start();
        
        int cnt = 0;
        do{
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(".");
            cnt++;
        }while(cnt < 10 );
        
        //#1 메인 스레드에도 일을 하도록 시킴        
        System.out.println("메인 스레드 종료");    
        
        //#2 runnable로 바꿔봐라
    }
}

----------------------------------- 
3-11
/day13/src/io/charstream/FileTest.java

package io.charstream;
import java.io.File;
public class FileTest {
    public static void main(String[] args) {
        // TODO File 클래스 테스트
        File f = new File("F:\\study\\sungjuk.txt");
        if(f.exists()){
            System.out.println(f.getName());
            System.out.println(f.getPath());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.length()+"바이트");
            System.out.println(f.delete());
        }else{
            System.out.println("존재하지 않는 파일입니다.");
        }
    }
}

----------------------------------- 
----------------------------------- 
###################################
4. 과제
-----------------------------------
성적표 파일 저장으로 만들기
----------------------------------- 
###################################
5. 과제 해결
----------------------------------- 
성적표 파일 저장으로 만들기
----------------------------------- 
###################################
6. tictactoe
----------------------------------- 
/Problem/src/tictactoe/UI.java

package tictactoe;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
 
public class UI extends JFrame{
    JPanel west,east;
    JButton button[] = new JButton[9];
    JButton reset, abstention;
    JLabel win, lose, draw;
    JTextField win_num, lose_num, draw_num;
    boolean isUserTurn = true;
    final int AI_NUM = 2;
    final int USER_NUM = 1;
    final int INIT = 0;
    int[] tictactoe = new int[9];
    public UI() throws IOException {
        west = new JPanel();        
        east = new JPanel();
        for (int i = 0; i < button.length; i++) {
            button[i] = new JButton(String.valueOf(i));    
            tictactoe[i] = 0;
        }        
        reset = new JButton("reset(초기화)");
        abstention = new JButton("abstention(기권)");    
        win = new JLabel("win(승)");
        lose = new JLabel("lose(패)");
        draw = new JLabel("draw(비김)");
        win_num = new JTextField();
        lose_num = new JTextField();
        draw_num = new JTextField();        
        
        west.setLayout(new GridLayout(3,3));
        for (int i = 0; i < button.length; i++) {
            //button[i].setIcon(new ImageIcon(ImageIO.read(new File("F:\\study\\java\\X.png"))));
            button[i].setBackground(Color.lightGray);
            button[i].addActionListener(new ButtonListener());
            west.add(button[i]);
        }
        reset.addActionListener(new ButtonListener());        
        
        east.setLayout(new GridLayout(42,2,2));
        east.add(reset);
        east.add(abstention);
        east.add(win);
        east.add(win_num);
        east.add(lose);
        east.add(lose_num);
        east.add(draw);
        east.add(draw_num);    
        
        setLayout(new GridLayout(1,2,5,5));        
        add(west);        
        add(east);        
        setSize(700400);
        setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
 
    private class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton j = (JButton)e.getSource();
            //배열과 Button에 값 및 색상변화, 특정 tictactoe 버튼을 눌렀을때
            for (int k = 0; k < button.length; k++) {
                if (tictactoe[k] == INIT) {
                    if (j.getText().equals(String.valueOf(k))) {
                        if (isUserTurn) {// user
                            j.setBackground(Color.red);
                            tictactoe[k] = USER_NUM;
                        } else {// ai
                            j.setBackground(Color.green);
                            tictactoe[k] = AI_NUM;
                        }
                    }
                    isUserTurn = !isUserTurn;
                }
            }
 
            if (j.getText().equals("reset(초기화)")) {
                for (int i = 0; i < button.length; i++) {
                    button[i].setBackground(Color.lightGray);
                    tictactoe[i] = INIT;
                }
            }
        }        
    }
 
    public static void main(String[] args) throws IOException {
        new UI();
    }
}


'OpenFrameWork' 카테고리의 다른 글

오픈프레임워크_Day16  (0) 2015.04.20
오픈프레임워크_Day15  (0) 2015.04.20
오픈프레임워크_Day13  (0) 2015.04.20
오픈프레임워크_Day12  (0) 2015.04.20
오픈프레임워크_Day11  (0) 2015.04.20
,