2022-10-11

JYR00·2022년 10월 11일
0

TIL

목록 보기
23/60

InputStream(InputStreamReader)/ Reader or FileReader(문자처리)
(1byte처리)

OutputStream (OutputStreamWriter) / Writer or FileWriter

FileWrite2Ex.java, MFrame.java, Mcolor.java

FlieWriter사용하여 예제하기

		super(320, 400);  //가로,세로
		setTitle("FileWriter");
		add(ta=new TextArea());
		Panel p = new Panel();
		p.add(tf = new TextField(30));
		p.add(save = new Button("SAVE"));
		ta.setEditable(false);  //편집 비활성화. 입력할 수 없게
//		tf.addActionListener(this);
//		save.addActionListener(this);
		add(p,BorderLayout.SOUTH);  //아래에 
		validate();

true면

이벤트를 할려면 인터페이스를 해야한다.
이벤트에는 버튼 누르기 등이 있다.



인터페이스 InterFace

  • 인터페이스에는 오로지 상수와 추상 메소드만이 들어갈 수 있다.
  • 모든 필드는 public static final이어야 하며(상수), 모든 메소드는 public abstract이어야 한다.(추상 메소드)
  • 인터페이스 직접 생성 불가. 아래와 같이 생성해야 한다.
class 클래스이름 implements 인터페이스이름 { ... }
  • inter : ~사이에
  • face : 얼굴

GUI : 윈도우가 대표적.
interface : 강제성을 가지고 있다. 이것만은 강제를 가지자 하고 태어남.
1) 서울개발자, 부산 개발자 서로 협업. 이것만은 강제로 정해놓은 것.
2) 삼성컴퓨터와 클래스. 상속받아 사용. 그러나 다중상속은 불가.
규격화 되어 있음(usb처럼) 상수할려면 static final 선언해야 하는데, 자동으로 상수선언이 된다.

사자

  • 포유
  • 육식
  • 척추

포유류

추상메서드 개념,

class Graphic implements Calcu{

	@Override
	public void plus(int i, int j) {
	}
}

public class InterEx1 {

	public static void main(String[] args) {

	}

FileWrite2 - 채팅저장,카운트다운 등

package ch13;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;

public class FileWrite2Ex extends MFrame implements ActionListener{
	
	
	TextArea ta;
	TextField tf;
	Button save;
	
	public FileWrite2Ex() {
		super(320, 400);  //가로,세로
		setTitle("FileWriter");
		add(ta=new TextArea());
		Panel p = new Panel();
		p.add(tf = new TextField(30));
		p.add(save = new Button("SAVE"));
		ta.setEditable(false);  //편집 비활성화. 입력할 수 없게
		tf.addActionListener(this);
		save.addActionListener(this);
		add(p,BorderLayout.SOUTH);  //아래에 
		validate();
	}
	
	@Override  //ctrl space 하니까 생김. 입력하고 엔터치면 호출되도록 만듦. e는 버튼치면 액션이벤트 객체가 내부에 만들어진 걸 가리킨다
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource(); //이벤트를 발생시킨 객체를 리턴 
		if(obj == tf) {
			//System.out.println("tf");
			ta.append(tf.getText() + "\n");
			tf.setText("");
			tf.requestFocus();
		} else if(obj == save){
//			System.out.println("save");
			saveFile(ta.getText());
			ta.setText("");
			try {
				for(int i =5; i>0; i--) {
					ta.setText("저장하였습니다." + i + "초 후에 사라집니다.");
					Thread.sleep(1000);//1초 후에 사라지게. 5부터 카운트 다운 시작.
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			ta.setText("");
	 } 
  }
	
	public void saveFile(String str) { // 입력한 값을 여기에 넣는다.
		try {
			long name = System.currentTimeMillis();
			FileWriter fw = new FileWriter("ch13/" + name + ".txt");
			fw.write(str);
			fw.flush();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}


	public static void main(String[] args) {
		new FileWrite2Ex();
	}

}

입력값이 숫자인지, 문자인지 구별하기

	@Override           //ctrl space 하니까 생김. 입력하고 엔터치면 호출되도록 만듦. e는 버튼치면 액션이벤트 객체가 내부에 만들어진 걸 가리킨다
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource(); //이벤트를 발생시킨 객체를 리턴 
		if(obj == tf) {
			System.out.println("tf");
		} else if(obj == save){
			System.out.println("save");
	} 
  }

분산화를 잘해야

입력값 볼 수 있게

	@Override           //ctrl space 하니까 생김. 입력하고 엔터치면 호출되도록 만듦. e는 버튼치면 액션이벤트 객체가 내부에 만들어진 걸 가리킨다
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource(); //이벤트를 발생시킨 객체를 리턴 
		if(obj == tf) {
			//System.out.println("tf");
			ta.append(tf.getText() + "\n");
			tf.setText("");
			tf.requestFocus();
		} else if(obj == save){
//			System.out.println("save");
	
	} 
  }

FileCopyEX1.java - 파일 복사 저장

package ch13;

import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;

public class FileCopyEX1 {

	public static void main(String[] args) {
		try {
			Scanner sc = new Scanner(System.in);
			System.out.println("원본파일 : ");
			String sFile = sc.nextLine();
			System.out.println("복사파일 : ");
			String cFile = sc.nextLine();
			FileReader fr = new FileReader("ch13/" + sFile);
			FileWriter fw = new FileWriter("ch13/" + cFile); //파일생성
			int c;
			while((c=fr.read())!=-1) {
				fw.write(c);
			}
			fw.close();
			fr.close();
			System.out.println("Copy End");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


FileCopyEx2

파일 내용 저장, 바꾸기

package ch13;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FileDialog;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;

public class FileCopyEx2 extends MFrame implements ActionListener{
	
	Button open, save;
	TextArea ta;
	FileDialog openDialog, saveDialog;
	String sourceDir;
	String sourceFile;
	
	public FileCopyEx2() {
		super(400, 500);
		setTitle("FileCopyEx2");
		add(ta = new TextArea());
		Panel p = new Panel();
		p.add(open = new Button("OPEN"));
		p.add(save = new Button("SAVE"));
		//ta.setEditable(false);
		open.addActionListener(this);  //연결
		save.addActionListener(this);
		add(p,BorderLayout.SOUTH);
		validate();
	}

	@Override

	public void actionPerformed(ActionEvent e) { // 이벤트 입장에서 버튼은 source
		Object obj = e.getSource();
		System.out.println(open.hashCode());
		System.out.println(save.hashCode());
		if(obj == open) { // 참조형은 객체의 주소값을 비교한다. 
			//비번 비교는 절대 ==사용하면 안된다. db비번과 사용자가 입력한 비번은 서로 다른 String 객체
			//dbPass == inputPass 죽었다깨도 false나온다.
			// dbPass.equals(inputPass) 이렇게 해야 한다.
			// equals는 내용이 동일한지 비교. ==는 주소값 비교
			
			openDialog = new FileDialog(this,"파일열기",FileDialog.LOAD);
			openDialog.setVisible(true);
			String dir, file;
			dir = openDialog.getDirectory();
			file = openDialog.getFile();
			fileReader(dir + file);
			
			
		}else if(obj == save) {
			saveDialog = new FileDialog(this,"파일저장",FileDialog.SAVE);
			saveDialog.setVisible(true);
			String dir, file;
			dir = openDialog.getDirectory();
			file = openDialog.getFile();
			fileWriter(dir + file);
		}
		
//		int i = 10;
//		int j =12;
		//System.out.println(i == j); //java 기본형은 값을 비교
	}
	
	public void fileReader(String file){
		try {
			FileReader fr = new FileReader(file);
			int c;
			String s="";  
			while((c=fr.read())!=-1) {
				s+=(char)c;
			}
			ta.setText(s);
			fr.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void fileWriter(String file){
		try {
			FileWriter fw = new FileWriter(file);
			fw.write(ta.getText());
			for (int i = 5; i > 0; i--) {
				ta.setText("저장 하였습니다. - " + i
						+"초후에 사라집니다.");
				Thread.sleep(1000);
			}
			ta.setText("");
			fw.flush();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new FileCopyEx2();
	}
}

버퍼링 buffer

버퍼에 그 다음 이미지가 없으니까

f12 누르고 톱니바퀴 누르고 debug disable javascript 쓰면 캡쳐가능


burfferReader / bufferWriter 버퍼를 이용해 읽고 쓰는 함수.

문자나 데이터를 한 자 한 자 보내는 것보다는 한 번에 보내는 것이 더 효율적이다.

  • 버퍼 : 데이터를 한 곳에서 다른 한 곳으로 전송하는 동안 일시적으로 그 데이터를 보관하는 임시 메모리 영역
  • 버퍼 플러시(buffer flush) : 버퍼에 남아 있는 데이터를 출력시킴(버퍼를 비우는 동작)
  • BufferedReader : 버퍼를 이용한 입력
  • BufferedWriter : 버퍼를 이용한 출력

BufferReaderEx1

package ch13;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferReaderEx1 {

	public static void main(String[] args) {
		
		InputStream is = System.in;
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		///////////////////////////////////////////////////////////////
		
		BufferedReader br1 =  //버퍼의 기능이 있으면서도 문자열로 받아들이며
				new BufferedReader(
				new InputStreamReader(System.in));
		
		String s = "";
		while(true) {
			try {
				s = br1.readLine(); //BufferedReader, readLine() 이거 하면 채팅 프로그램 거의 다 완성된다.
				System.out.println("출력 : " + s);
			} catch (Exception e) {
				e.printStackTrace(); //에러가 난 위치를 보여줌.
			}
		}
	}

}

BufferedWriterEx

package ch13;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;

public class BufferedWriterEx {

	public static void main(String[] args) {

		String s = "오늘은 즐거운 화요일입니다.";
		BufferedWriter bw =
				new BufferedWriter(
						new OutputStreamWriter(System.out));
		try {
			bw.write(s,0,s.length());
			bw.newLine();
			bw.write(s);
			bw.flush();
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

InetAddressEx ip 주소 관련 예제

package ch14;

import java.net.InetAddress;

public class InetAddressEx {

	public static void main(String[] args) {
		try {
			InetAddress add = InetAddress.getLocalHost(); //java.net에 있는 거.
			System.out.println("Host Name : " + add.getHostName());
			System.out.println("Host Address : " + add.getHostAddress());
			add = InetAddress.getByName("auction.co.kr");
			System.out.println("옥션 Host Adress : " + add.getHostAddress());
			InetAddress adds[] = InetAddress.getAllByName("naver.com");
			System.out.println("-------------");
			for(int i = 0; i<adds.length; i++) {
				System.out.println("naver : " + adds[i]);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

InetAddressFrameEx

package ch14;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;

public class InetAddressFrameEx extends MFrame 
implements ActionListener{
	
	TextField tf;
	TextArea ta;
	Button lookup;
	InetAddress intAddr;
	
	public InetAddressFrameEx() {
		setTitle("InetAddress Example");
		Panel p = new Panel();
		p.setLayout(new BorderLayout());
		p.add("North",new Label("호스트이름"));
		p.add(tf = new TextField("",40));
		p.add("South",lookup = new Button("호스트 정보 얻기"));
		tf.addActionListener(this);
		lookup.addActionListener(this);
		add("North",p);
		ta = new TextArea("인터넷주소\n");
		ta.setFont(new Font("Dialog",Font.BOLD,15));
		ta.setForeground(Color.BLUE);
		ta.setEditable(false);
		add(ta);
		validate();
	}
	
	
	public void actionPerformed(ActionEvent e) {
//		InetAddress adds[] = getAllByName("naver.com","daum.com");
		Object obj = e.getSource();
		if(obj == lookup||obj==tf) {
			try {
				String host = tf.getText().trim();
				intAddr = InetAddress.getByName(host);
				String add = intAddr.getHostName();
				String ip = intAddr.getHostAddress();
				ta.append("" + add + "\n");
				ta.append("" + ip + "\n");
				
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			tf.setText("");
			tf.requestFocus();
	}
	


	public static void main(String[] args) {
		new InetAddressFrameEx();
//		for(int i = 0; i<add.length; i++) {
//			
//			System.out.println("naver : " + adds[i]);
//			System.out.println("인터넷 주소 : \t" + adds[i].getHostAddress());
//			add = InetAddress.getByName("auction.co.kr");
//			System.out.println("옥션 Host Adress : " + add.getHostAddress());
			
		}
			
	}
}

UrlEx : 소스 가져오기

package ch14;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class UrlEx {

	public static void main(String[] args) {
    String spec = "https://search.naver.com:80/search.naver?where=nexearch&"
    	+"sm=top_hty&fbm=1&ie=utf8&query=java#top";
    try {
		URL url = new URL(spec);
		System.out.println("Protocol: " + url.getProtocol());
		System.out.println("Host: " + url.getHost());
		System.out.println("Port: " + url.getPort());
		System.out.println("Path: " + url.getPath());
		System.out.println("Query : " + url.getQuery());
		System.out.println("FileName: " + url.getFile());
		System.out.println("Ref: " + url.getRef());
		url = new URL("http://jspstudy.co.kr/main/main.jsp");
		BufferedReader br = new BufferedReader(   //자바와 네이버 연결
				new InputStreamReader(url.openStream(),"UTF-8"));
		String line = "";
		while(true) {
			line = br.readLine();
			if(line == null) break;
			System.out.println(line);
		}
		br.close();
		System.out.println("===================");
		System.out.println("END~~");
	} catch (Exception e) {
		e.printStackTrace();
	}
  }
}

채팅 프로그램 1단계

스레드(thread)

prcess(프로세스)
-> 프로그램 단위

단일 thread

  • 무전기
    말하는 ( )
    듣는 ( )
    => 한번에 한 가지만 가능
    지금까지는 단일스레드였다.

멀티 thread

  • 휴대폰
    말하는( )
    듣는( )
    => 여러가지 동시에 가능

소켓(socket)


















0개의 댓글