FileEx01
package day13;
import java.io.File;
import java.io.IOException;
import java.util.Date;
public class FileEx01 {
public static void main(String[] args) {
//File f = new File("C:\\Windows\\system.ini");
//경로 명을 적을 때 역슬래쉬 두개 (이스케이프 문자로 인식하지 않게).
File f = new File("c:\\Windows\\system.ini");
//만약에 복붙해서 넣었는데 파일 크기 인식을 못하면 타이핑해서 넣기
long size = f.length(); //파일 크기
System.out.println(size);
String filename = f.getName();//파일 명
System.out.println(filename);
String path = f.getPath(); //파일 경로
System.out.println(path);
String parent = f.getParent(); //파일의 부모 경로
System.out.println(parent);
String ap = f.getAbsolutePath(); //절대 경로
System.out.println(ap);
if(f.isFile()) { //파일인지 디렉터리인지 확인
System.out.println(f.getPath() + "는 파일입니다.");
}else if(f.isDirectory()) {
System.out.println(f.getPath()+"는 폴더입니다.");
}
System.out.println(f.isHidden()); //숨김 파일인가
System.out.println(f.canRead()); //읽기 속성 가지고 있는가
System.out.println(f.canWrite()); //쓰기 속성 있는가
System.out.println(f.lastModified()); //최종 수정 시간. 밀리초로 나옴
System.out.println(new Date(f.lastModified())); //최종 수정 시간 이렇게 하면 날짜 형식 맞춰 나옴
File f2 = new File("c:\\Windows");
File[] list = f2.listFiles(); //파일 객체 가져오기
for(int i = 0; i<list.length;i++) {
System.out.println(list[i].getName());
System.out.println("\t파일크기: "+ list[i].length());
}
//파일 만들기
File f3 = new File("c:\\test\\Kor.txt"); //폴더까지 만들었으나 아직 파일은 없음.
try {
f3.createNewFile();//파일 생성.
} catch (IOException e) {
System.out.println(e);
}
//디렉토리 만들기
File f4 = new File("c:\\test\\iotest");
if(!f4.exists()) { //f4가 존재하지 않으면
System.out.println("없으니 생성");
f4.mkdir(); //메이크 디렉터리. 폴더 생성
}
}
}
FileInEx01
package day13; //파일 읽어오기
import java.io.FileInputStream;
public class FileInEx01 {
public static void main(String[] args) {
byte [] b = new byte[6];
FileInputStream fin = null;
try {
fin = new FileInputStream("c:\\test\\test.out");
int i = 0;// 배열 인덱스로 사용
int c; //읽은 파일 임시 저장 변수
while(((c =fin.read())!= -1)) { //읽어서 c에게 담았다.
//호출해서 담은 c가 -1이 아닐때까지 반복. EOF를 만나면 -1가 됨.
b[i]=(byte)c; //하나씩 읽어와야하는 이유가 있다면 이렇게
i++;
}
//배열과 데이터 크기 맞고, 준비해둔 배열을 던져주던 알아서 읽어 채워준다.
//fin.read(b); //while 대신
//확인 출력
for(byte bb : b) {
System.out.print(bb+" ");
}System.out.println();
}catch(Exception e) {
e.printStackTrace();
}finally{
if(fin != null)
try{fin.close();}catch(Exception e) {e.printStackTrace();}
}
}
}
FileInEx02
package day13; //동영상이나 이미지 주고 받을 때 바이트 스트림 사용. 한글이면 문자 스트림
import java.io.FileInputStream;
public class FileInEx02 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("c:\\test\\fos.txt");
int c;
while((c = fis.read())!= -1) {
System.out.print((char)c); //한글은 2 byte라서 깨짐.
}System.out.println();
}catch(Exception e) {
e.printStackTrace();
}finally {
if(fis != null) {
try {fis.close();}catch(Exception e) {e.printStackTrace();}
}
}
}
}
FileOutEx01
package day13; //파일쓰기
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class FileOutEx01 {
public static void main(String[] args) {
byte[] b = {6,4,7,9,3,-2};
try {
//파일 출력 스트림 생성. 통로 하나 만듦.
//파일을 자바 외부로 내보내겠다..
FileOutputStream fout = new FileOutputStream("c:\\test\\test.out");
//파일 쓰기
// for(int i =0; i <b.length; i++) { //낱개로 쓰기
// fout.write(b[i]);
// }
fout.write(b); //배열 통으로 보내서 쓰기
//스트림 닫기
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
FileOutEx02
package day13;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Scanner;
public class FileOutEx02 {
public static void main(String[] args) {
//파일에 저장할 문자열들을 str에 담을 준비
String file, str;
Date date = new Date();
Scanner sc =new Scanner (System.in);
str = "파일 생성 시간\n\n" + date + "\n\n";
System.out.println("파일 이름을 입력하세요>>> ");
file = sc.nextLine(); // c:\\test\\fos.txt
System.out.println("저장할 문자열을 입력하세요>>> ");
str += sc.nextLine();
byte[] strByte = str.getBytes(); //바이트 단위로 전송하니 문자열을
//바이트로 변경
FileOutputStream fout = null; //꼭 바깥에 선언하기..
try {
fout = new FileOutputStream(file);
fout.write(strByte);
}catch(IOException e){
e.printStackTrace();
}finally {
if(fout != null)try{fout.close();//트라이문 안에서 선언해도 되지만 만약 저 안에서 할 경우엔 에러가 날 경우엔
//바로 캐치로 넘어가서 클로즈가 안되서 누수가 발생. 파이널리로 빼준다.
}catch(Exception e) {e.printStackTrace();}
if(fout != null)try{sc.close();
}catch(Exception e) {e.printStackTrace();}
}
System.out.println(file + "파일을 성공적으로 저장했습니다.");
}
}
InputReadEx01
package day13;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class InputReadEx01 {
public static void main(String[] args) {
// InputStreamReader 바이트 스트림 -> 문자 스트림
FileInputStream fin = null;
InputStreamReader in = null;
try {
fin = new FileInputStream("c:\\test\\fos.txt"); //바이트 스트림을
in = new InputStreamReader(fin); //workspace가 UTF-8 //문자 스트림으로 한번 감싸서 사용
System.out.println("encoding: " + in.getEncoding());
int c;
while((c = in.read()) != -1) {
System.out.print((char)c);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(fin != null) {
try{fin.close();}catch(Exception e) {e.printStackTrace();}
try{in.close();}catch(Exception e) {e.printStackTrace();}
}
}
}
}
OutWriterEx01
package day13;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class OutWriterEx01 {
public static void main(String[] args) {
FileOutputStream fos= null;
OutputStreamWriter out = null;
Scanner sc = new Scanner (System.in);
String str = "파일 생성 시간: " + new java.util.Date()+ "\n\n";
System.out.println("메세지 입력>> ");
str += sc.nextLine();
try {
fos = new FileOutputStream("c:\\test\\outStrWrt.txt");
out= new OutputStreamWriter(fos);
System.out.println("encoding: " + out.getEncoding()); //인코딩 세팅 뭐로 됐나 출력확인
out.write(str);
out.flush(); //닫기 전에 스트림 비우기
}catch(Exception e) {
e.printStackTrace();
}finally {
if (fos != null) {
try {fos.close();}catch(Exception e) {e.printStackTrace();}
try {out.close();}catch(Exception e) {e.printStackTrace();}
try {sc.close();}catch(Exception e) {e.printStackTrace();}
}
}
}
}
ThEx01
package day13;
class TimerThread extends Thread{
int n = 0;
@Override
public void run() {
while(true) {
n++;
System.out.println(n);
try {
sleep(1000);//1000밀리초는 1초
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}//와일
}//런
}//클래스
public class ThEx01 {
public static void main(String[] args) { //main스레드 기본적으로 1개 존재
System.out.println("main 메서드 실행 ");
TimerThread th = new TimerThread();
th.start();//스레드 시작
System.out.println("main 메서드 종료");
//메서드는 스레드 실행하고 메인 메서드 실행하고 종료.
//스레드가 여러개라서 메인 메서드가 끝나도 스레드가 전부 종료 되지는 않는
}
}
ThEx03
package day13;
class ThreadEx extends Thread{
@Override
public void run() {
for(int i =0; i < 1000; i++) {
System.out.println("run");
}
}
}
public class ThEx03 {
public static void main(String[] args) {
ThreadEx th= new ThreadEx();
ThreadEx th2= new ThreadEx();
th.start();
th2.start();
//th.run() 단순 메서드 호출, 스레드 등록 안돼서 메인 스레드로만 실행
for(int i =0; i <1000; i++) {
System.out.println("main");
}
}
}
ThEx04
package day13;
//Runnable 인터페이스 구현
class TimeRunnable implements Runnable{
int n =0;
@Override
public void run() {
System.out.println(Thread.currentThread().getName()); //현재 돌고 있는 스레드 이름 출력
while(true) {
n++;
System.out.println(n);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
}
public class ThEx04 {
public static void main(String[] args) {
Thread th = new Thread(new TimeRunnable());
th.start();
Thread th2 = new Thread(new TimeRunnable());
th2.start();
}
}
ThEx05
package day13;
import javax.swing.JOptionPane;
class ThreadTime extends Thread{
@Override
public void run() {
System.out.println("10초 안에 값을 입력해야 합니다.");
//GUI 방식으로 입력 받기. 무조건 문자열
String input = JOptionPane.showInputDialog("아무 값이나 입력하세요. ");
ThEx05.inputCheck=true;
System.out.println("입력하신 값은 "+input+"입니다.");
}
}
class ThreadInput extends Thread{
@Override
public void run() {
for(int i =10; i>0; i--) {
if(ThEx05.inputCheck) {return;} //입력했으니 런 메서드 강제 종료->스레드 종료
System.out.println(i);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();}
}
System.out.println("10초 동안 값이 입력되지 않아 종료합니다.");
System.exit(0); //프로그램 종료
}
}
public class ThEx05 {
static boolean inputCheck = false; //입력했는지 체크하는 공용변수
//값이 있으면 트루 없으면 폴스
public static void main(String[] args) {
ThreadTime th = new ThreadTime(); //타이머
ThreadInput inputTh = new ThreadInput(); //입력
// th.setPriority(Thread.MAX_PRIORITY); //우선 순위10. 가장 높다.
// System.out.println(th.getPriority());
th.start();
inputTh.start();
}
}
InetEx01
package day13;
import java.net.InetAddress;
public class InetEx01 {
public static void main(String[] args) throws Exception {
InetAddress addr1 = InetAddress.getByName("naver.com");
System.out.println(addr1);
InetAddress addr2 = InetAddress.getLocalHost();
System.out.println(addr2);
}
}