System.out.println("Hello, World");

1. 이클립스 font 설정하기 위해서 Window -> preference로 진입한다.



2. 그후 Java탭에서 -> Editor -> Syntax Coloring으로 들어간뒤 오른쪽 메뉴에서 Java를 선택하여 

바꾸고 싶은 항목을 선택하여 색깔이라든지, Bold체 등 바꿔주면 된다. 



Posted by 김마농

Thread를 extends하는 예제

예제

ThreadTest1

public class ThreadTest1 {
	public static void main(String[] args) {
		Print1to30Thread pt1 = new Print1to30Thread();
		pt1.start();
		PrintAtoZThread pt2 = new PrintAtoZThread();
		pt2.start();
		PrintAtoZLowThread pt3 = new PrintAtoZLowThread();
		pt3.start();
		//동시에 같이 일을 하게 되어서 랜덤으로 스레드가 실행된다.		
	}
}

PrintAtoZThread
//A에서 Z까지 출력하는 Thread
public class PrintAtoZThread extends Thread{
	public void run(){
		//Thread의 실행 코드가 들어온다.
		for(int i = 65; i<91; i++)
		{
			System.out.print((char)i);
		}
		System.out.println();
	}
}
PrintAtoZLowThread
public class PrintAtoZLowThread extends Thread{
	public void run(){
		for(int i=97; i<97+26; i++){
			System.out.print((char)i);
		}
		System.out.println();
	}
}
Print1to30Thread
public class Print1to30Thread extends Thread{
	public void run(){
		for(int i=0; i<31; i++){
			System.out.print(i);
		}System.out.println();
	}
}

<결과>


결과는 위와 같이 랜덤으로 출력된다. 그 이유는 메소드처럼 순서대로 실행되는게 아니라 Thread는 동시에 실행되므로 결과값들이 위와 같이 상이하게 나오게 된다.


-Runnable에서 Running으로 변화시켜주는건 프로그래머는 모르고 JVM이 처리한다.

-다른일을 처리하다가 다른쪽에서 Running상태가 되고 자신의 상태가 Runnable상태가 된후 다시 Running으로 되돌아간다면 아까 멈췄던 곳에서 다시 시작한다.


Thread.Sleep(int 밀리초)

특정 Thread가 Dead(완료)될때까지 실행중인 thread를 멈춘다.(실행중인 Thread를 밀리초동안 멈춘다.)

멈춘후 해당 Thread는 Blocked상태가 된다.


Thread객체.join()

특정 Thread가 Dead(완료)될때가지 실행중인 Thread를 멈춘다.(메소드 오버로딩 되있음)

Thread가 멈춰서 Blocked상태가 된다.


Thread를 implements하는 예제

ThreadTest
public class ThreadTest {
	public static void main(String[] args) {
		Print1to99Thread pt1  = new Print1to99Thread();
		Print100to900Thread pt2 = new Print100to900Thread();
		Thread t1 = new Thread(pt1);//Thread 객체를 생성해서 담아줘야 한다.
		Thread t2 = new Thread(pt2);//Thread 객체를 생성해서 담아줘야 한다.
		t1.start();		
		t2.start();
		System.out.println("메인종료");
		//모든 스레드가 Dead하면 끝난다.		
	}
}

Print100to900Thread
public class Print100to900Thread implements Runnable{
	public void run() {
		for(int i=100; i<=900; i=i+100){
			System.out.println(i);
		}	
		//메소드 수행이 끝나면 Dead한다.
	}
}
Print1to99Thread
public class Print1to99Thread implements Runnable{
	public void run() {
		for(int i=0; i<99; i=i+5){
			System.out.println(i);
		}		
		//메소드 수행이 끝나면 Dead한다.
	}
}

<결과>


Thread Sleep 예제 
ThreadSleepTest

public class GoThread extends Thread{
	public void run(){
		for(int i = 0; i<10; i++){
			System.out.println("GoThread: " +i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

ComeThread
public class ComeThread extends Thread{
	public void run(){
		for(int i=0; i<10; i++){
			System.out.println("Come Thread : " + i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}	
}

<결과>

1초마다 파일을 생성하면서 20초마다 파일을 긁어오는 Thread 예제  


ThreadTest
public class ThreadTest {
	public static void main(String[] args) {
		MakeFileThread t1 = new MakeFileThread();
		MoveFileThread t2 = new MoveFileThread();
		t1.start();		
		t2.start();
	}
}

MakeFileThread
public class MakeFileThread extends Thread{
	//매 1초에 하나의 파일을 생성한다. 1분동안 - FIle명 costa.1, costa.2, costa.3
	public void run(){
		for(int i=1; i<60; i++){
			//만약 디렉토리 파일이 없다면 생성해줘야 한다.
			//File dir = new File("D:\\temp");
			//if(!dir.exits)
			//dir.mkdir(); 디렉토리가 없으면 만들어라
			File file = new File("D:\\temp\\costa."+i);
			Boolean flag;
			try {
				flag = file.createNewFile();
				//파일 생성하기
				System.out.println("파일 생성 여부 : "+i+"번째"+flag);
			} catch (IOException e) {
				e.printStackTrace();
			}			
			try {
				//1초간 멈추기
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

MoveFileThread
public class MoveFileThread extends Thread {
	// makeThread에서 만든 파일을 다른 경로로 이동 = 매 20초당 한번씩- 1분동안 처리한다.
	public void run() {
		for (int i = 0; i < 3; i++) {
			//for(int i=0; i<3; i++){
			//원본파일이 있는 디렉토리 내의 파일 리스트 ㅂ루러오기
			//File newFilesDir = new File("D:\\temp");
			//String [] fileList = newsFilesDir.list();
			//파일 옮기기
			//for(String f : fileList){
			//if(file.isDirectory())//만약 디렉토리면 안옮기게따
			//continue;
			//File file =new File(newsWifle,f);
			//file.renameTo(new File("D:\\temp2");
			//Thread.sleep(20000); 20초동안 잔다.
			try {
				Thread.sleep(20000);//20초 쉬었다가 밑에 있는 거 실행한다.
			} catch (InterruptedException e) {
				e.printStackTrace();				
			}
			for (int j = 0;  j<60; j++) {
				//원본파일이 있는 디렉토리내의 파일 리스트 불러오기
				File origin = new File("D:\\temp\\costa." + j);
				File newfile = new File("D:\\temp2\\costa." + j);
				Boolean flag = origin.renameTo(newfile);
				System.out.println("파일 옮겨졌을까 : " + flag);
			}				
		}
	}
}




Thread를 join을 이용하는 예제 

SumThread

public class SumThread extends Thread{
	private int first;
	private int last;
	private int sum;
	public SumThread(int first, int last){
		this.first = first;
		this.last = last;		
	}
	public int getSum(){
		return sum;
	}	
	public void run(){
		//first에서 last까지 1씩 더하기
		//1+2+3+4+5+6+7+8+9+10
		for(int i = first; i<=last; i++){
			sum = sum+i;
		}
	}
}
ThreadTest
public class ThreadTest {
	public static void main(String[] args) {
		SumThread t1 = new SumThread(1, 10);		
		t1.start();		
		try {
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}//t1이 끝날때까지 블럭하겠다.
		int sum = t1.getSum();
		System.out.println("1부터 10까지의 총합 : " +sum);
		}
}

만약 ThreadTest에서 t1.join을 사용하지 않을 경우에는 t.start()가 SumThread의 getSum()보다 빨리 실행된다. 빨리 실행되는 이유는 main이 더 짧고 getSun()에서는 연산이 들어가있기 때문에 main이 더 빨리 실행되게 된다. 

또한 Thread.sleep()을 사용할수 있지만 멈춰있는 시간이 연산되는 시간보다 적을수 있기 때문에 join을 사용해야 한다. 

Posted by 김마농






Posted by 김마농
public class ObjectStreamTest {
	private static String fileName = "D:\\person.obj";//매개변수 받은 객체를 파일로 출력
	public static void writeobject(Object obj){
		//인수로 받은 객체를 person.obj에 출력
		//ObjectOutputStream 이용, 객체를 출력 - 객체 직렬화, 출력 대상 : instance 변수의 값들( attribute)
		
		ObjectOutputStream oos =null;
		try {
			//연결하면서 필터까지 추가한 내용
			oos = new ObjectOutputStream(new FileOutputStream(fileName));
			//쓰기작업시작-writeObject(object)
			oos.writeObject(obj);
			//매개변수로 받은 객체를 넘겨준다.
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(oos!=null)
			{
				try {
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}		
	}
	public static Object readObject(){
		//person.obj파일에 젖아된 객체 정보를 읽어들여 다시 객체로 만든다.
		//ObjectInputStream - 객체를 입력받는 메소드 : 객체 역직렬화
		//메소드 : readObject() : Objectream
		ObjectInputStream ois = null;
		Object obj = null;
		try {
			ois = new ObjectInputStream (new FileInputStream(fileName));
			//읽기
			obj = ois.readObject();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(ois!=null)
			{
				try {
					ois.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return obj;
		
	}
	public static void main(String[] args) {
		//PersonDTO p = new PersonDTO("id-111","112312","홍길동",123);
		//writeobject(p);//직렬화가 안되서 Exception오류가 나게 된다.
		Object obj = readObject();
		PersonDTO dto = (PersonDTO)obj;
		System.out.println(dto);
	}
}
Posted by 김마농
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 ObjectStreamTest2 {
	private static String fileName = "D:\\person.obj";//매개변수 받은 객체를 파일로 출력
	public static void writeobject(Object obj){
		//인수로 받은 객체를 person.obj에 출력
		//ObjectOutputStream 이용, 객체를 출력 - 객체 직렬화, 출력 대상 : instance 변수의 값들( attribute)
		
		ObjectOutputStream oos =null;
		try {
			//연결하면서 필터까지 추가한 내용
			oos = new ObjectOutputStream(new FileOutputStream(fileName));
			//쓰기작업시작-writeObject(object)
			oos.writeObject(obj);
			//매개변수로 받은 객체를 넘겨준다.
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(oos!=null)
			{
				try {
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}		
	}

	public static void main(String[] args) {
		PersonDTO p = new PersonDTO("id-111","112312","홍길동",123);
		writeobject(p);//직렬화가 안되서 Exception오류가 나게 된다.		
	}
}



import java.io.Serializable;

public class PersonDTO implements Serializable{
	private String id;
	private String password;
	private String name;
	private int age;
	//생성자, setter, getter tostring
	public PersonDTO(){}
	public PersonDTO(String id, String password, String name, int age) {
		this.id = id;
		this.password = password;
		this.name = name;
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "PersonDTO [id=" + id + ", password=" + password + ", name="
				+ name + ", age=" + age + "]";
	}
}
Posted by 김마농
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class BufferReaderWriterTest {
	public static void main(String[] args) {
		//Filter Steram을 이용한 입출력
		//BufferedRedaer와 PrintWriter를 이용해 news.txt->news3.txt로 입출/력
		FileReader fr = null;
		FileWriter fw = null;
		//Filter스트림
		BufferedReader br = null;//버퍼를 이용, 라인단위로 읽는 기능
		PrintWriter pw = null;//데이터 포맷에 맞게 출력, println(), print()
		try{
			//1-1 d연결
			fr = new FileReader("D:\\news.txt");
			fw = new FileWriter("D:\\news4.txt");
			//1-2 filter 스트림 추가
			br = new BufferedReader(fr);
			//fr 노드 스트림에다가 BufferedReader 필터를 추가해준다.
			pw = new PrintWriter(fw);//한꺼번에 출력하는는 경우에 쓰인다.
			
			//pw = new PrintWriter(fw,true);//true : auto flush - println()하면 바로 출력된다.
			//쓸때마다 출력해야 하는 경우는(true)를 더하면 된다, 바로바로 출력하는 채팅에 쓰이게 된다.
			//fw 노드 스트림에다가 PrintWriter 필터를 추가해준다,
			//2. read(BufferedReader)와 writer(PrintWriter)를 해준다.
			String str = br.readLine();//엔터를 기준으로 읽어들임(엔터는 안읽는다.)
			while(str!=null)//EOF : null을 리턴
			{
				pw.println(str);
				System.out.println(str);
				str=br.readLine();				
			}
			//pw.flush();//buffer에 있는 데이터를 최종 출력장소로 밀어내는 메소드
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();	
		}finally{
			//3. 연결끊기 - Filter를 끊으면 된다.
			if(br!=null)
			{
				try{
				br.close();
				}catch(IOException e){
				e.printStackTrace();
				}
			}
			if(pw!=null){
				pw.close();//throws안함, 내부적으로 처리함
			}
		}
	}
}
Posted by 김마농


자바에서는 모든 입출력에서 스트림이라는 개념을 사용하는데, 이것은 C언어와 유닉스에서 온 개념이다. 자바에서는 위와 같은 그림처럼 스트림을 직접 파일에 연결되는 '노드 스트림'과 노드 스트림에 연결하여 다른 처리를 해 주는 '필터 스트림'으로 구분하고 있다.(파일이라고 했지만, 자바에서는 키보드, 모니터, 메모리, 네트워크 상의 리소스도 마찬가지로 취급하고 있다.)

위 그림에서는 노드 스트림과 필터 스트림을 자세히 표현한 그림으로, 역시 바이트 데이터의 저수지(파일이나 키보드 모니터, 메모리, 인터넷 리소스 등)에 직접 연결되어 있는 부분이 노드 스트림이다. 대표적인 입력 노드 스트림은 InputStream 클래스다. 키보드에서 입려을 받는 System.in도 바로 이 InputStream 클래스의 객체다. 대표적인 출력 노드 스트림은 OutoutStream 클래스다. 저수지 데이터로부터 데이터를 하나 가져오면 당연히 노드 스트림을 통하게 된다. 

◎ 입력 스트림

InputStream 클래스는 바이트 단위로 읽기 때문에 한글 등의 이유로 캐릭터 단위로 읽으려면 InputStreamReader 클래스를 연결해서 사용해야 한다. InputStream 클래스는 추상 클래스이기 때문에 바로 사용하는 것은 불가능하고, 반드시 상속받아서 쓰거나 InputStream 클래스의 서브 클래스를 사용해야 한다. 
다음은 InputStream 클래스의 객체인 System.in에 InputStreamReader 클래스의 객체를 연결하여 키보드로부터 문자열을 입력받는 예제다.

InputStreamReaderTest.java

import java.io.IOException;
import java.io.InputStreamReader;

public class InputStreamReaderTest {
	public static void main(String[] args) {
		InputStreamReader in = new InputStreamReader(System.in);		
		try{
			while(true){
				int i=in.read();
			char myChar=(char)i;
			System.out.print(myChar);
		}
	}catch(IOException e){
		System.out.println(e.toString());			
		}
	}
}

◎ FileInputStream과 FileReader
FileInput 클래스는 Input클래스의 서브 클래스로, 파일로부터 바이트 단위로 읽는 입력 스트림이다. 캐릭터 단위로 읽으려면 FIleReader클래스를 사용하면 된다. FileInputStream 클래슨 파일 이름을 바로 적거나 FIle클래스를 사용해서 생성 할 수 있다.

◎ BufferedInputStream과 BufferedReader
BufferedInputStream 클래스는 InputStream 클래스에 버퍼를 추가한 스트림이다. BufferedInputStream 클래스를 사용하면, 프로그램에서 데이터를 읽어올때 요청한 데이터보다 많은 양의 데이터를 미리 버퍼에 읽어 놓았다가 다음 요청때 돌려주기 때문에 프로그램이 기다리는 시간이 줄어들어서 전체적인 수행속도가 빨라 진다. BufferedInputStream 클래스는 필터 스트림이기 때문에 그 자체로는 쓸 수 없고, InputStream 클래스의 객체를 인수로 받아서 생성 해야 한다. 이와 마찬가지로 InputStreamReader클래스에 버퍼를 추가 한 것이 BufferedReader 클래스이다. BufferedReader 클래스를 생성할 때 InputStreamReader 클래스의 객체를 인수로 주면, 버퍼를 사용하면서 캐릭터 단위로 데이터를 읽는 스트림이 생성된다. 

◎ OutputStream과 OutputStreamWriter
OutputStream클래스는 대표적은 출력 스트림이다. OutputStream 클래스는 바이트 단위로 데이터를 출력하기 때문에, 한글과 같은 비영어궈 문자를 출력하려면 캐릭터 단위로 출력하는 OutputStreamWriter 클래스를 연결해서 사용해야 한다. OutputStream 클래스도 InputStream 클래스와 마찬가지로 추상 클래스이기 때문에 바로 사용할수는 없고, 서브 클래스를 사용해야 한다. OutputStream 클래스는 모든 출력 스트림의 슈퍼클래스이기 때문에 OutputStream 클래스의 모든 메소드는 서브클래스에서 사용할 수 있다.

◎ FileOutPutStream과 FilwWriter
FileOutputStream 클래스는 OutputStream 클래스의 서브 클래스로, 파일에 바이트 단위로 출력하는 출력 스트림이다. 캐릭터 단위로 출력하려면 FileWriter 클래스를 사용하면 된다.

◎ BufferedOutputStream과 BufferedWriter
BufferedOutputStream 클래스는 BufferedInputStream 클래스처럼 버퍼 처리를 하는 출력 스트림이다. 프로그램에서 BufferedOutputStream 클래스로 만든 출력 슽림에 출력을 하면, 바로 장치(파일이나 모니터, 네트워크 소켓등)에 출력되지 않고, 메모리의 버퍼에 출력된다. 버퍼가 가득 차면 자동으로 장치에 출력되기 때문에 프로그램이 매번 저장장치에 기록되길 기다리는 OutputStream에 비해 전체적인 수행 속도가 빨라진다.
BufferedOutputStream 클래스는 필터 스트림이기 때문에 그 자체로는 쓸 수 없고, OutputStream 클래스의 객체를 인수로 주어 생성해야 한다. 이와 마찬가지로 OutputStreamWriter 클래스에 버퍼 처리를 한 것이 BufferedWriter클래스다. BufferedWriter 클래스를 생성 할 때 OutputStreamWriter 클래스의 객체를 인수로 주면, 버퍼를 사용하면서 캐릭터 단위로 출력하는 스트림이 생성된다. 

◎ DataOutputStream
입력 스트림인 DataInputStream 클래스의 대응 되는 출력 스트림이 DataOutputStream 클래스다. DataOutputStream 클래스는 자바의 기본 데이터형으로 출력할 수 있도록 해주는 출력 스트림이다. DataInputStream 클래스처럼 DataOutputStream 클래스도 바이트 단위로 데이터를 처리하기 때문에 별로 인듯 하다. DataInputStream 클래스보다는 PrintStream클래스나 PrintWriter클래스를 사용하는 편이 좋다.

◎ PrintStream와 PrintWriter
PrintStream 클래스는 필터 스트림으로 OutputStream 클래스의 객체를 인수로 받아서 생성할 수 있다. PrintStream 클래스는 OutputStrema 클래스의 모든 기능을 단 2개의 메소드인 print()메소드와 println() 메소드로 출력 할 수 있도록 해주는 강력하고 편리한 출력 스트림이다. PrintStream 클래스의 print()메소드와 println()메소드는 메소드 오버로딩을 이ㅛㅇㅇ해서 주어지는 데이터형에 상관없이 출력 할 수 있도록 되어 있다.

Posted by 김마농

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReaderWriterTest{
		public static void main(String[] args) {
			FileReader fr = null;
			FileWriter fw = null;
			//d:\news.txt를 읽어서 news2.txt로 쓴다 char[]로 받아서 쓰이게 된당
			try{
				fr = new FileReader("D:\\news.txt");
				fw = new FileWriter("D:\\news2.txt");
				long l1 = System.currentTimeMillis();
				char[] data = new char[100];
				int length = fr.read(data);
				int count=0;
				
				while(length !=-1){
					fw.write(data,0,length);
					length = fr.read(data);
					count++;
				}
				long l2 = System.currentTimeMillis();
				System.out.println(l2-l1);
				System.out.println(count);					
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(fr!=null){//만약 fi가 null이 아닐 경우
					try {
						fr.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(fw!=null){
					try {
						fw.close();
					} catch (IOException e) {
						e.printStackTrace();
						}
					}
				}	
			}
		}

Posted by 김마농

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class FileStreamArrayTest { public static void main(String[] args) { FileInputStream fi = null; FileOutputStream fo = null; try { //1. 연결 fi = new FileInputStream("D:\\Desert.jpg");//연결 fo = new FileOutputStream("D:\\Desert3.jpg");//덮어쓰기 //fo=new FileOutputStream("D:\\Desert2.jpg",true);//이어쓰기 파일크기가 2배가 되어버린다. //2. I/O작업(읽는 작업, 출력작업) long l1 = System.currentTimeMillis(); int count =0; byte[] buff = new byte[10000];//읽은 데이터는 배열에 있다. int length = fi.read(buff);//몇바이트 읽었는지 while(length != -1){ fo.write(buff,0,length);// 0번부터 length까지 쓰게 된다. 그냥 buff로 쓰면 기존에 있던 바이트들이 중복처리되서 파일 용량이 이전것보다 크게 써지게 된다.

length =fi.read(buff);// count++; } long l2 = System.currentTimeMillis(); System.out.println(l2-l1+"초"); System.out.println("반복횟수 : "+count); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(fi!=null){//만약 fi가 null이 아닐 경우 try { fi.close(); } catch (IOException e) { e.printStackTrace(); } } if(fo!=null){ try { fo.close(); } catch (IOException e) { e.printStackTrace(); } } } } }


Posted by 김마농

<파일을 읽어서 출력해주기 : 파일 복사>


import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class FileStreamTest { public static void main(String[] args) { FileInputStream fi = null; FileOutputStream fo = null; try { //1. 연결 fi = new FileInputStream("D:\\Desert.jpg");//연결 //fo = new FileOutputStream("D:\\Desert2.jpg");//덮어쓰기 fo=new FileOutputStream("D:\\Desert2.jpg",true);//이어쓰기 파일크기가 2배가 되어버린다. 만약 텍스트파일을 이어쓰기 했을 경우 텍스트 파일이 복사된다. //2. I/O작업(읽는 작업, 출력작업) int data = fi.read();//1바이트, 여기서 먼저 1바이트 읽게 된다. int count =0; long l1 = System.currentTimeMillis();//시간 계산 while(data!=-1){ fo.write(data);//출력 count++; data = fi.read();//입력 } long l2 = System.currentTimeMillis();//시간 계산 System.out.println("읽은 횟수 : "+count); System.out.println((l2-l1)/1000+"초"); //3. 연결 끊기 //fi.close();//연결 끊기 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(fi!=null){//만약 fi가 null이 아닐 경우 try { fi.close(); } catch (IOException e) { e.printStackTrace(); } } if(fo!=null){ try { fo.close(); } catch (IOException e) { e.printStackTrace(); } } } } }


Posted by 김마농