노력과 삽질 퇴적물

JAVA: 자바 기초 (3) 본문

프로그래밍note/언어. JAVA & JDK 계열

JAVA: 자바 기초 (3)

MTG 2012. 7. 17. 10:47

JAVA: 자바 기초 (1)

JAVA: 자바 기초 (2)

JAVA: 자바 기초 (3)

JAVA: 자바 기초 (4)





08장. 스레드

 1. 스레드 기본 사용법

-> run()을 재정의하고, start()로 실행시켜야 한다.

-> 점연산자[.]를 통해서

     sleep(), setDaemon(), join()

     setPriority()

     등이 가능.

//package chapter08;

class Threading_1 extends Thread

{

public void run() // run() 재정의[오버라이드]

{

int i = 1;

while(i <= 50)

{

System.out.print ( "run_"+ i + "\t");

try

{

Thread.sleep(1000);

}catch(InterruptedException e){

System.out.print("냉동상태");

}

if( i%5 == 0 )

{

System.out.print("\n");

}

i++;

}

}

}



 public class Exam91

{

public static void main( String[] ar )

{

Threading_1 th1 = new Threading_2();

th1.setDaemon(true);//true값으로 종속스레드화. 기본적으로 독립스레드

th1.start(); // 스레드 실행

char i = 'A';

System.out.print("public static void main( String[] ar )\n\n");

while( i <= 'Z' )

{

System.out.print(i + "\t");

try

{

th2.join(5000); //지정시간동안 메인을 점유

}catch(InterruptedException error) {

System.out.print("냉동상태, main");

}

if( i%4 == 0 )

{

System.out.print("\n");

}

i++;

}

System.out.print("\n");

System.out.print("END. public static void main( String[] ar )\n");

}

}


JAVA: 스레드에서 세부설명 참조가능.






09장. JAVA API

 1. 수학 클래스

-> 수학계산에 유용한 클래스

//package chapter09;

public class Exam102

{

public static void main( String[] ar )

{

double x = 123.5678;


int a1 = (int)Math.round(x);

System.out.print("a1 : " + a1 + "\n");

int a2 = (int)Math.round(x * 10.0) / 10;

System.out.print("a2 : " + a2 + "\n");

double a3 = (int)Math.round(x * 100.0) / 100;

System.out.print("a3 : " + a3 + "\n\n");

int b1 = (int)Math.floor(x);

System.out.print("b1 : " + b1 + "\n");

double b2 = (int)Math.floor(x * 10.0) / 10;

System.out.print("b2 : " + b2 + "\n");

double b3 = (int)Math.round(x * 100.0) / 100;

System.out.print("b3 : " + b3 + "\n\n");

int c1 = (int)Math.ceil(x);

System.out.print("c1 : " + c1 + "\n");

double c2 = (int)Math.floor(x * 10.0) / 10;

System.out.print("c2 : " + c2 + "\n");

double c3 = (int)Math.round(x * 100.0) / 100;

System.out.print("c3 : " + c3 + "\n\n");


System.out.print("절대값 : " + Math.abs(-20) + "\n");

System.out.print("최대값 : " + Math.max(10, 20) + "\n");

System.out.print("최소값 : " + Math.min(24.5f, 1.3f) + "\n");

System.out.print("2의 3승 : " + Math.pow(2, 3) + "\n");

}

}




 2. 문자열 토큰 및 출력양식지정

//package chapter09;

import java.text.DecimalFormat;

import java.util.StringTokenizer;


public class Exam104

{

public static void main( String[] ar )

{

String context = "수소, 헬륨, 리튬, 베릴륨";

StringTokenizer str1 = new StringTokenizer(context);

StringTokenizer str2 = new StringTokenizer(context, ", ");

//특정기호나 단어를 토큰으로 지정가능.

double x = 12345.6789;

System.out.print("문자열내 토큰갯수: "+str1.countTokens()+"\n");

while(str1.hasMoreTokens())

{

System.out.print(str1.nextToken() + "\n");

}

System.out.print("==============================\n");

System.out.print("문자열내 토큰갯수 : "+str2.countTokens()+"\n");

while(str2.hasMoreTokens())

{

System.out.print(str2.nextToken() + "-");

}

System.out.print("\n");

System.out.print("==============================\n\n");

System.out.print("DecimalFormat() \n");

System.out.print("x : " + x + "\n\n");

DecimalFormat a1 = new DecimalFormat("0");

System.out.print("a1 : " + a1.format(x) + "\n");

DecimalFormat a2 = new DecimalFormat("#");

System.out.print("a2 : " + a2.format(x) + "\n");

DecimalFormat a3 = new DecimalFormat("0000000.0");  //반올림

System.out.print("a3 : " + a3.format(x) + "\n");

DecimalFormat a4 = new DecimalFormat("#.#");  //반올림

System.out.print("a4 : " + a4.format(x) + "\n");

DecimalFormat a5 = new DecimalFormat(".0");  //반올림

System.out.print("a5 : " + a5.format(x) + "\n");

DecimalFormat a6 = new DecimalFormat(".####");  //소수점 버림

System.out.print("a6 : " + a6.format(x) + "\n");

DecimalFormat a7 = new DecimalFormat("#,###,###,###");

System.out.print("a7 : " + a7.format(x) + "\n\n");



StringBuffer str = new StringBuffer("JAVA Basis");

System.out.print("str : " + str + "\n");

System.out.print("길이 : " + str.length() + "\n");

System.out.print("용량 : " + str.capacity() + "\n");

System.out.print("str.insert() : "+str.insert(5, "_끼워넣기_")+"\n");

System.out.print("str.charAt() : " + str.charAt(5) + "\n");

System.out.print("str.reverse() : " + str.reverse() + "\n");

System.out.print("str : " + str);

}

}




 3. API문서 활용하기

-> 원하는 기능에 맞는 API클래스를 import시켜서 사용하면 된다.

     해당 포스트에서는 문서를 참조해서 사용하는 방법을 간단하게 설명합니다.

-> 공식 API 도큐먼트(웹)

     Java™ PlatformStandard Ed. 6 웹문서(영문)

     Java™ PlatformStandard Ed. 7 웹문서(영문)

가령 달력처럼 날짜에 관련된 기능을 구현한다면,


카테고리를 수동으로 찾는 방법만 알고 있어서 현재는 이렇게 해야 한다.


Method Summary를 보면 자신이 구현할 기능에 필요한 매소드(함수)들을 찾아볼수 있다.

Modifier and Type => 함수의 반환타임

Method and Description => 함수(매소드)의 매개인수와 기능설명.


단순히 API를 가져다 쓸 경우, Constructor Detail까지 살펴볼 필요성은 없다.

DX에서도 원하는 기능을 하는 함수를 찾아서 쓰는걸 익히지 굳이 해당 함수의 내부를 샅샅이 파악하진 않는다고 했다.






10장. 파일 입출력  예외처리

 1. 경로를 이용한 파일접근

-> 기본경로는 해당프로젝트 폴더내 최상위 경로에 있다.

-> ..\\프로젝트_폴더명     상대경로값

경로내 파일부재시경로내 파일존재시

//package chapter10;

import java.io.File;


public class Exam118

{

public static void main( String[] message )

{

// 지정경로 파일접근

File[] root = File.listRoots();

File f_dir = new File("..\\JAVA_basis");//경로에 \를 2개씩인게 JAVA식

String[] str = f_dir.list();//지정된 경로 리스트를 문자열로 저장.

File exam = new File(f_dir, "JAVA_basis-CH10.txt");//프로젝트 폴더내

//상위 디렉토리 출력

for(int i = 0; i < root.length; i++)

{

System.out.print(root[i] + "\n");

}

//파일목록 출력

for(int i = 0; i < str.length; i++)

{

System.out.print(str[i] + "\n");

}

//파일정보 불러오기

System.out.print("파일명 : " + exam.getName() + "\n"

+ "경로명 : " + exam.getParent() + "\n"

+ "쓰기가능 : " + exam.canWrite() + "\n"

+ "읽기가능 : " + exam.canRead() + "\n"

+ "파일크기 : " + exam.length() + "byte" + "\n");

}

}




 2. 파일쓰기, OutputStream

-> 기본경로는 해당프로젝트 폴더내 최상위 경로에 있다.

-> 호출 및 생성: 파일out-버퍼out-데이터out   [F-B-D]

     종료: 데이터out-버퍼out-파일out              [D-B-F]

//package chapter09;

import java.io.File;

import java.io.FileOutputStream;

import java.io.BufferedOutputStream;

import java.io.DataOutputStream;

import java.io.FileNotFoundException;//파일존재 에러

import java.io.IOException;//입출력 에러


public class Exam121

{

public static void main( String[] message ) throws IOException

{

try

{

File file = new File("..\\test_Stream.txt");//생성 파일이름 지정.

FileOutputStream fos = new FileOutputStream(file);

BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

DataOutputStream dos = new DataOutputStream(bos);

//데이터 객체로 파일쓰기

dos.writeInt(20);

dos.writeFloat(30.4f);

dos.writeChar('x');

dos.writeDouble(0.5);

dos.close();

bos.close();

fos.close();

System.out.print("파일출력 완료");

}catch(FileNotFoundException e) { System.out.print("FILE ERROR, 파일이 없습니다" + e);

}catch(IOException io) { System.out.print("IO ERROR, 파일이 없습니다" + io);

}

}

}




 3. 파일읽기, InputStream

-> 호출 및 생성: 파일in-버퍼in-데이터in [F-B-D]

     종료: 데이터in-버퍼in-파일in            [D-B-F]

-> 굉장히 단순하게는 File과 FileInputStream객체만으로도 가능하다.

//package chapter09;

import java.io.File;

import java.io.FileInputStream;

import java.io.BufferedInputStream;

import java.io.DataInputStream;

import java.io.FileNotFoundException;//파일존재 에러

import java.io.IOException;//입출력 에러


public class Exam122

{

public static void main( String[] message ) throws IOException

{

try//

{

File file = new File("..\\test_Stream.txt");

FileInputStream fis = new FileInputStream(file);        // 객체생성, File

BufferedInputStream bis = new BufferedInputStream(fis, 1024); // 객체생성, Buffered

DataInputStream dis = new DataInputStream(bis);         // 객체생성, Data

//데이터 객체로 파일쓰기

int a = dis.readInt();

float b = dis.readFloat();

char c = dis.readChar();

double d = dis.readDouble();

System.out.print(a + "\t" + b + "\t" + c + "\t" + d + "\n");

dis.close();// 객체종료, Data

bis.close();// 객체종료, Buffered

fis.close();// 객체종료, File

System.out.print("파일출력 완료");

}catch(FileNotFoundException e) { System.out.print("FILE ERROR, 파일이 없습니다" + e);

}catch(IOException io) { System.out.print("IO ERROR, 파일이 없습니다" + io);

}

}

}




 4. 파일쓰기, Writer

-> 마무리떄 PrintWriter만 close

-> PrintWriter는 print()매소드나 write()매소드로 파일쓰기 가능.

//package chapter09;

import java.io.File;

import java.io.FileWriter;

import java.io.PrintWriter;

import java.io.BufferedWriter;

import java.io.IOException;//입출력 에러

import java.io.FileNotFoundException;//파일존재 에러


public class Exam123

{

public static void main( String[] ar ) throws IOException

{

try

{

//객체 생성

File file = new File("..\\test_Writer.txt");

FileWriter fw = new FileWriter(file);//FileWriter

BufferedWriter bw = new BufferedWriter(fw, 1024);//BufferedWriter

PrintWriter pw = new PrintWriter(bw);//PrintWriter, 버퍼에 넣어짐

pw.print("---Buffered Reader/Writer는---");

bw.newLine();//BufferedWriter는 줄바꿈 메서드 제공.

pw.write("---버퍼를 이용한 IO---");

pw.write(2012 + "\n");//PrintWriter에서 \n는 파일에서 깨진글자로 저장.

pw.close();//PrintWriter 종료.

System.out.print("파일출력 완료");

}catch(FileNotFoundException e) {

System.out.print("FILE ERROR, 파일이 없습니다" + e);

}catch(IOException io) {

System.out.print("IO ERROR, 파일이 없습니다" + io);

}

}

}

(파일에 저장된 내용)

---Buffered Reader/Writer는---

---버퍼를 이용한 IO---2012




 5. 파일읽기, Reader

-> 마무리떄 BufferedReader만 close


//package chapter09;

import java.io.File;

import java.io.FileReader;

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.IOException;


public class Exam124

{

public static void main( String[] message ) throws IOException

{

try

{

//객체 생성

File file = new File("..\\test_Writer.txt");

FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr, 1024);

String ln_buf = "";

for(int i = 0; (ln_buf = br.readLine()) != null; i++)

{

System.out.print(i + " : " + ln_buf + "\n");

}

br.close(); // 버퍼 객체 종료

System.out.print("파일출력 완료");

}catch(FileNotFoundException e) { System.out.print("FILE ERROR, 파일이 없습니다" + e + "\n");

}catch(IOException io) { System.out.print("IO ERROR, 파일이 없습니다" + io + "\n");

}

}

}




 6. 클래스 쓰기, ObjectOutputStream

-> 클래스 호출 및 객체생성: 파일out-버퍼out-데이터out [F-B-D]

     종료: 데이터out-버퍼out-파일out                           [D-B-F]

//package chapter09;

import java.io.File;

import java.io.FileOutputStream;

import java.io.BufferedOutputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

import java.io.IOException;

import java.io.FileNotFoundException;


class Test implements Serializable//클래스 쓰기에는 이게 반드시 상속되어야 함

{

int x = 10;

float y = 24.5f;

char z = 'a';

}


public class Exam127

{

public static void main( String[] ar ) throws IOException

{

try

{

Test a = new Test();

File file = new File("..\\ObjectIOStream.txt");

FileOutputStream fos = new FileOutputStream(file);           //파일

BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);//버퍼

ObjectOutputStream oos = new ObjectOutputStream(bos);      //오브젝트

oos.writeObject(a);


//스트림 종료.

oos.close(); //오브젝트

bos.close(); //버퍼

fos.close(); //파일.

System.out.print("OK");

}catch(FileNotFoundException e){ System.out.print("File ERROR" + e);

}catch(IOException e){ System.out.print("IO ERROR" + e);

}

}

}




 7. 클래스 읽기, ObjectInputStream

-> 클래스 호출 및 객체 생성: 파일in-버퍼in-데이터in [F-B-D]

     종료: 데이터in-버퍼in-파일in                           [D-B-F]

//package chapter09;

import java.io.File;

import java.io.FileInputStream;

import java.io.BufferedInputStream;

import java.io.ObjectInputStream;

import java.io.IOException;

import java.io.FileNotFoundException;


public class Exam128

{

public static void main( String[] ar ) throws IOException

{

try

{

File file = new File("..\\ObjectIOStream.txt");

FileInputStream fis = new FileInputStream(file);

BufferedInputStream bis = new BufferedInputStream(fis, 1024);

ObjectInputStream ois = new ObjectInputStream(bis);

Object obj = ois.readObject();

Test a = (Test)obj;

System.out.print(a.x + "\n");

System.out.print(a.y + "\n");

System.out.print(a.z + "\n");

ois.close();

bis.close();

fis.close();

}catch(FileNotFoundException e){  System.out.print("File ERROR" + e);

}catch(IOException e){  System.out.print("IO ERROR" + e);

}catch(ClassNotFoundException e){ System.out.print("Class ERROR" + e);

}

}

}




* 부록


Stream IO

Reader/Writer IO

 Object IO

Input

파일내용 출력

 File file
 FileInputStream fis

 BufferedInputStream bis
 DataInputStream dis
//데이터 객체로 파일쓰기
 dis.read...();

// 객체종료
 dis.close();
 bis.close();
 fis.close();
 File file
 FileReader fr
 BufferedReader br

 br.readLine()

 br.close(); // 버퍼종료
 File file
 FileInputStream fis
 BufferedInputStream bis
 ObjectInputStream ois

 ois.readObject();

 ois.close();
 bis.close();
 fis.close();

Output

파일생성

 File file
 FileOutputStream fos
 BufferedOutputStream bos
 DataOutputStream dos

 dos.write...();

 dos.close();
 bos.close();
 fos.close();

 File file

 FileWriter fw

 BufferedWriter bw

 PrintWriter pw


 pw.print();

 bw.newLine();//줄바꿈

 pw.write();


 pw.close();//PrintWriter 종료.

//implements Serializable필수
 File file

 FileOutputStream fos

 BufferedOutputStream bos
 ObjectOutputStream oos

 oos.writeObject(a);

//스트림 종료.
 oos.close(); //오브젝트
 bos.close(); //버퍼
 fos.close(); //파일

'프로그래밍note > 언어. JAVA & JDK 계열' 카테고리의 다른 글

JAVA: 자바 기초 (4)  (0) 2012.08.08
이클립스: 설정 및 팁  (0) 2012.07.20
JAVA: 자바 기초 (2)  (0) 2012.07.11
JAVA: 자바 기초 (1)  (0) 2012.06.07
안드로이드: 개발환경 구축  (0) 2011.11.23