레이블이 Stream인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Stream인 게시물을 표시합니다. 모든 게시물 표시

2015년 10월 21일 수요일

150922 - 자바 12일차 Stream / Thread

150922 - Stream / Thread
*****


io


1. Stream 구조

(1) 단방향
(2) 원칙적으로 순차적 - 예외도 있다.
(3) 지연발생가능
(4) 어떤 장치를 사용하던 간에 사용법은 동일하다. - 스트림은 일종의 필터. 하나만 알면 지장이 없다.
(5) 자바에서는 입출력에 관련된 모든 클래스들을 Java.io 패키지에서 제공.
(6) nio = new input output - 개별적으로 파보기

2. 자바에서 제공하는 Stream 방식

(1) Byte Stream 방식 - 데이터를 1byte씩 보내고 받는 방식
            - InputStream     
               read()
            - OutputStream
               write()
(2) Character Stream 방식 - 데이터를 한문자씩 보내고 받는 방식 ( at least 2byte ) 

            -Reader (문자단위로 사용할때 가장 부모클래스)
               read()
            -Writer
               write()
(3) PrintStream 방식  - 출력을 조금 더 쉽게 하기 위한 . ex) println, print

            -print()
            -println() - 모니터, 파일, 네트워크등 출력 가능



3. 자주 사용할만한 클래스들  

(1) FileInputStream , FileOutputStream  --]Filter class       --> Data persistance   -->> Database ( too heavy and big ) then, -- > File

(2) DataInputStream , DataOutputStream  --]

기본형 8 타입의 데이터를 주고 받을때 사용이 편하다.

(3) RandomAccessFile - 유일하게 임의로 접근하는 방법을 제공한다.
java.lang.Object
java.io.RandomAccessFile

---------> 입출력 X. 랜덤으로 일을 처리하기 때문에 인풋, 아웃풋 스트림을 상속받지 않는다. 

(4) PrintWriter

(5) ObjectInputStream , ObjectOutputStream - byteStream 방식

(6) File


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

*****Thread  -  한 작업

1) processs program   파일이 저장만 되어있으면 프로그램, 실행이 되면 프로세스

2) 단일 프로세스 멀티프로세스

하나의 프로세스 에서 실횅하는 작업 단위
3) 
멀티쓰레드 - 
4: 든프로그램은 반드시 하나이상의 쓰레드를 포함


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


-----------------------------과제 ----------------------------------------


입력값 1,2,3,4,5 를 주고 5초 카운팅 한후 결과값이 나오게 만들어라


package prjThread;

class ThreadDemo44 extends Thread implements Runnable {

public ThreadDemo44(String string) {

}

@Override
public void run() {
int sum = 0;

for (int i = 1; i <= 5; i++) {

try {
sleep(100);
} catch (InterruptedException e) {

e.printStackTrace();
}

sum += i;
System.out.println("입력 : " + i);
}
try {
sleep(5000);
} catch (InterruptedException e) {

e.printStackTrace();
}
System.out.println("\n결과 : " + sum);
}

}

public class ThreadTest44 {
public static void main(String[] args) {

ThreadDemo44 t1 = new ThreadDemo44(null);
 Thread tt1 = new Thread(t1);
 tt1.start();
System.out.println("잠시 기다려주세요");

int cnt = 0;
do {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("...\t");
cnt++;
} while (cnt < 5);

}


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


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


텍스트파일 cmd 로 복사하기


package CharStream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileTest22 {

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

// TODO test.txt 내용을 test2.txt로 복사

FileInputStream fin = new FileInputStream("E:\\Test3.txt");
FileOutputStream fout = new FileOutputStream("E:\\Test4.txt",true);//트루로 내용 중첩

int input = 0;
OutputStream os = System.out;
while (true) {
input = fin.read();
if (input == -1) // -1 이라는 값은 ctrl + z 일때 -1이 전달되고 실제로 -1 을쓰면 2글자로인식한다 
break;

os.write((char) input);
os.flush();
fout.write((char) input);
}
fin.close();
fout.close();

}

}

150921 - Generic / Exception / throw - throws / Stream / try-catch

150921 - 자바 11일차 Generic / Exception / throw - throws / Stream / try-catch 
****Generic

1. 용도
1) 특정 타입 ( 객체 타입 ) 을 미리 검사
- 사전에 잘못된 데이터 타입을 미리 체크
2) C++ 의 Template 과 비슷한 기능\

2. 사용문법
클래스 <객체타입>  참조변수 =  new 클래스의 생성자 <객체타입>

3. 작성문법
class 클래스이름 <특정 키워드>{

}


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


package Generic;

import java.util.Vector;

public class GenericTest {

public static void main(String[] args) {
// TODO Auto-generated method stub

//Vector vec = new Vector(); 문자열 타입만 저장할수 있지만, 숫자를 써도 오류가 나지않아 미스코딩을 하기 쉽다.
Vector<String> vec = new Vector<String>();  //Vector 값에 제너릭 으로 String 을줘서 문자열만 받도록 했다  밑의 숫자100 란에 오류가생긴다.
vec.add("hell O");
vec.add("HHell o");
vec.add("hEEll o");
//...
//vec.add(100);
/* String str = null; //비어있는값  - 창조할 주소가 없을때.  0값 이 아니라 無값
for (int i=0 ; i<vec.size(); i++){
str = (String)vec.get(i);
System.out.println(str);
*/
//for(변수 : 배열 또는 컬렉션)
//배열이나 컬렉션 안에있는 데이터를 모두 사용할 때 까지 반복을 계속한다.
for (String str : vec){
System.out.println(str);
}
}
}





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


package Generic;


class GenericDemo <T>{
private T value;
// 내가 원하는 타입을 실행중에 결정을 할수 있게,  동적 바인딩.
// 데모클래스 자체를 제너릭 으로 생성하여야 한다.

public GenericDemo(T i){

value = i;
}

public T getValue() {
return value;
}

}

public class GenericTest2 {

public static void main(String[] args) {
// TODO Template 의 용도
GenericDemo<Integer> demo1 = new GenericDemo(100);  //<>안에는 객체타입만 올수 있음  int 형의 wrap 클래스 
System.out.println(demo1.getValue()); //래퍼클래스 integer Double String
GenericDemo <Double>demo2 = new GenericDemo(3.14);
System.out.println(demo2.getValue());
GenericDemo <String>demo3 = new GenericDemo("Generic Test...");
System.out.println(demo3.getValue());

}
}



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

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


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

****예외처리

1. 예외(에러)가 발생했을 경우 / 에러에 대한 제어권을 시스템 ( JVM ) 이 아니라 개발자가 가질수 있게 하는 방법.

2. 왜?

1) 예외 가 발생했을 때 메세지에 대한 표현 문제 
2) 프로그램의 비정상적 종료



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


package prjException;

public class ExcTest1 {
public static void main ( String args []){
int[] arr = new int [3];
System.out.println("예외처리 첫번쨰 테스트...");
int i;
try{
arr[7] = 100;
 i= 10/0;
}
catch( ArrayIndexOutOfBoundsException err){
System.out.println("배열넘침잼 : " + err.toString());
}
catch(IndexOutOfBoundsException err){
System.out.println("아오바에서잡음 ㅋ");
}
catch(RuntimeException err){
System.out.println("런타임에서잡음 ㅋ");
}
catch(Exception err){
System.out.println("!!!!!!!!!!!!!!!!!!!!!!예외발생!!!!!!!!!!!!!!!!!!!!!!");
}
System.out.println("이게 보이냐?");

}
}




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


package prjException;

import java.io.IOException;

public class ExcTest2 {

public static void main(String[] args) {
// TODO 예외처리 두번째 예제
System.out.println("한문자 입력 : ");
char input =' ';
try {
input = (char) System.in.read();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("What charactor U input : " + input);

}

}




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




3. 주요 키워드
1) try
2) catch
3) throw
-예외를 던진다.
-용도 : 테스트 나 처리위치 변경
-한개만 던질수 있다
-반드시 블럭(메서드) 안에 선언되어야 한다
4) throws
-예외들을 던진다
-용도 : 대신 처리를 부탁
-여러개 던질수 있다
-반드시 블럭 (메서드)바깥에 선언되어야 한다
5) finally



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


package prjException;

public class ThrowTest {

public static void main(String[] args) {
// TODO Throw 예제
try{
System.out.println("여기는 try블럭..");
throw new ArithmeticException("일부러 예외발생시킴..");
}
catch ( ArithmeticException err){
System.out.println("ArithmeticException err occur");
System.out.println(err.getMessage());
}
System.out.println("End of try/catch Test");
}

}




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



package prjException;

public class ThrowsTest {

static void second() throws ArithmeticException {
System.out.println("second() 호출");

throw new ArithmeticException();

}

static void first() throws Throwable {
System.out.println("first() 호출");
second();
}

// try{
// }
// catch(ArithmeticException err)
// System.out.println("first에서 작동");
// }

// 세컨드 에서 발생한 문제를 throws 로 퍼스트로넘겼음

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

// TODO Thows 예제

try {
first();
catch (Exception err) {
System.out.println("메인으로넘어감");
}
catch (Throwable err){
System.out.println("throwable 처리됨");
}

}

}




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


4. try~ catch block
try{ 
예외가 발생할 가능성이 있는 코드
}
catch (매개변수){
처리
}

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

try {
...
}
catch(...){ 자식클래스(구체적이다)
...
}
catch(...){
...
}
catch(...){ 부모클래스 (자식이못찾으면 뭐라도걸러내긴한다) Exception / Throwable
...
}



5. Throwable

get massage

printstackTrace

toString



**************

io


1.Stream 구조

1) 단방향
2) 순차적
3) 지연 발생 가능
4) 어떤 장치를 사용하던간에 사용법은 동일
5) 자바에서는 java.io라는 패키지에서 제공


2. 자바에서 제공하는  Stream 방식

1) Byte Stream 방식
-input Stream
read()

-output Stream
write()

2) Character Stream 방식 
-Reader
read()

Writer
write()

3) PrintStream 방식
print().
println().



3. 자주 사용할 만한 클래스들

1)FileInputStream, FileOutputStream


2)DataInputStream, DataOutputStream


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


package ByteStream;

import java.io.IOException;

public class ByteTest1 {

public static void main(String[] args) throws IOException {
// TODO Byte Stream 예제 1

System.out.println("문자열 입력 (10문자까지) :");
byte data[] = new byte[10];

System.in.read(data);

for (int i=0; i<data.length; i++)
System.out.println((char)data[i]);
}
}





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


package ByteStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ByteTest2 {

public static void main(String[] args) throws IOException {
// TODO ByteStream 방식 예제 2
streamTest(System.in,System.out);
}
public static void streamTest(InputStream is, OutputStream os )throws IOException{
int input = 0;
while(true) { 
input = is.read();
if (input == -1) // -1 이라는 값은 ctrl + z 일때 -1이 전달되고 실제로 -1 을쓰면 2글자로인식한다 
break;
//System.out.println((char)input);
os.write((char) input);
}

}

}




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




package ByteStream;

import java.io.FileInputStream;
import java.io.IOException;

public class FileTest {

public static void main(String[] args) throws IOException{
// TODO 파일로부터 입력받아 모니터로 출력
FileInputStream fin = new FileInputStream("E:\\Test1.txt" );
int input = 0;
while(true) { 
input = fin.read();
if (input == -1) // -1 이라는 값은 ctrl + z 일때 -1이 전달되고 실제로 -1 을쓰면 2글자로인식한다 
break;
System.out.write((char)input);
}

}
}
----------------------------------------------------------------------