TIL 06 - JAVA

eyan31·2022년 6월 20일
0

TIL

목록 보기
6/25
post-thumbnail

TIL | 06.20의 기록

FileWriter

콘솔에서 문자열을 줄단위로 입력받아 파일로 쓰기

//문자 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("문자입력=");
String inData = br.readLine();
//객체 생성
File file = new File("c://testFolder","outputTest.java");
FileWriter fw = new FileWriter(file);
			
fw.write(inData, 0, inData.length());
fw.close();

FileInputStream, FileOutputStream

파일 복사하기

기존 파일 orgFile 객체와 이를 복사한 tarFile 객체있다고 가정

FileInputStream fis = new FileInputStream(orgFile); //읽기
FileOutputStream fos = new FileOutputStream(tarFile); //쓰기
//파일의 내용을 읽어서 저장할 배열 
byte sourceCode[] = new byte[(int)orgFile.length()]; //length반환값 long보다 커서 int로 변환
//읽어온 바이트수를 리턴해준다.
int cnt = fis.read(sourceCode);
//쓰기
fos.write(sourceCode, 0, cnt);

DataInputStream, DataOutputStream

원래 데이터타입으로 파일 읽고 쓰기

int dataInt = 234; double dataDouble = 12.45; boolean dataBoo = true; char dataChar = 'z';

//원래 데이터형으로 파일 쓰기
File f = new File("c://testFolder/data.txt");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
dos.writeInt(dataInt); dos.writeDouble(dataDouble); 
dos.writeBoolean(dataBoolean); dos.writeChar(dataChar); 
dos.close();

// Data형으로 저장된 데이터 읽어오기 (쓰여진 순서대로 읽어와야 한다)
DataInputStream dis = new DataInputStream(new FileInputStream(f));
dis.readInt(); dis.readDouble();
dis.readBoolean(); dis.readChar();

ObjectOutputStream

객체를 파일로 사용하기 위해서는 직렬화가 되어있어야 한다.
Serializable 인터페이스를 상속받은 클래스는 직렬화가 되어있으며, 이러한 클래스는 객체생성시 new를 안붙여도 가능하다.

//파일로 객체 저장하기
File f = new File("C://testFolder/object.txt");
FileOutputStream fos = new FileOutputStream(f);
		
ObjectOutputStream oos = new ObjectOutputStream(fos);
		
oos.writeObject(o1);
oos.writeObject(o2);
		
oos.close(); //close는 마지막부터 역순으로 작성
fos.close();

ObjectInputStream

파일에 저장된 객체 입력하기

File file = new File("c://testFolder/object.txt");
			
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
			
Calendar date =(Calendar)ois.readObject(); //원래 타입으로 형변환
MemberVO vo = (MemberVO)ois.readObject(); //형변환

RandomAccessFile

비순차적 입출력을 가능하게 한다. 파일의 원하는 위치에 읽기, 쓰기 가능.
mode : r->읽기전용, w->쓰기전용, rw->읽기쓰기 모두 가능

File f = new File("c://testFolder/random.txt");
RandomAccessFile raf = new RandomAccessFile(f, "rw");
//쓰기
String str = "JAVA Random Access File Test...";
raf.writeChars(str);
//원하는 위치(포인트)로 이동하여 쓰기
String txt = "자바프로그래밍";
raf.seek(5);
raf.writeChars(txt);
//읽기
raf.seek(10);
byte data[]	= new byte[10];
int cnt = raf.read(data, 0, data.length);
System.out.println(new String(data)); //byte를 문자열로

Thread

스레드는 프로세스 내 하나의 실행흐름이다. 스레드는 자바가상머신의 스레드 스케줄러가 자동으로 관리한다. 동시에 여러개의 스레드를 실행할 수 도 있다. 이에 대한 방법 두가지가 있다.

  1. Thread 클래스 이용
    Thread 클래스를 상속받고 스레드 처리가 필요한 코드를 run()메소드에 오버라이딩하면 스레드 스케줄러가 실행을 관리한다.
public class ThreadTest1 extends Thread{
String threadName;
this.threadName = threadName;
public void run() {
	for(int i=1; ;i++) {
		System.out.println(threadName+"->"+i);
	}
}
public static void main(String[] args) {
	ThreadTest1 t1 = new ThreadTest1();
	ThreadTest1 t2 = new ThreadTest1();
    //run()메소드는 start()메소드를 이용하여 호출가능하다.
	t1.start();
	t2.start();
  1. Runnable 인터페이스 이용
    Runnable 인터페이스를 상속받고 스레드 처리가 필요한 코드를 run()메소드에 오버라이딩하면 스레드 스케줄러가 실행 관리한다. Thread 클래스를 상속받는 경우에는, Thread외에 다른 클래스를 상속받아야 하는 상황이 오면 문제가 생긴다. (extends는 하나만 상속가능하기 때문에)
    public class ThreadTest2 implements Runnable : Runnable 상속
    Thread.sleep() : 지정한 밀리초만큼 대기한다. (static)
public static void main(String[] args) {//main은 기본적으로 스레드
ThreadTest2 t1 = new ThreadTest2("first 스레드");
ThreadTest2 t2 = new ThreadTest2("second 스레드");
		
// 인터페이스를 상속받으면 추상메소드이기 때문에 Thread객체로 만든다.
Thread obj1 = new Thread(t1);
Thread obj2 = new Thread(t2);
		
obj1.start();
obj2.start();

동기화 (Synchronizer)

synchronized 키워드를 통해 스레드 메소드를 동기화할 수 있다. 동기화하면 메소드를 동시에 실행불가능하다.
public synchronized void run() {} : 반환형 앞에 synchronized 작성
Thread.currentThread().getName() : 현재 실행중인 스레드 객체의 스레드명
this.wait() : 현재 실행중인 스레드 중지

public void run() {
	synchronized(this) {// 동기화 하고 싶은 부분만 sync로 묶어 사용해도 된다.
		for(int i=1; i<=7; i++) {
			try {Thread.sleep(1000);}catch(Exception e) {}
			getCash(1000);
		}
	}
}

통신

TCP

간단하게 말하면 서버와 클라이언트의 통신이다.

InetAddress

ip에 관련된 객체를 생성한다.

InetAddress ia = InetAddress.getLocalHost();
String ip = ia.getHostAddress();// 내컴퓨터 ip
String name = ia.getHostName(); // 컴퓨터 이름 또는 url주소

// 도메인 이용한 InetAddress를 얻어오기
InetAddress ia2 = InetAddress.getByName("www.naver.com");
System.out.println("ia2.address->"+ ia2.getHostAddress());
// ip를 이용한 InetAddress를 얻어오기 (객체 만들기)
InetAddress ia3 = InetAddress.getByName("120.50.131.112");
System.out.println("ia3.address->"+ ia3.getHostAddress());
// 여러개의 InetAddress 객체 얻어오기
InetAddress[] ia4 = InetAddress.getAllByName("www.naver.com");
for(InetAddress i : ia4) {
	System.out.println("ia4.address->"+i.getHostAddress());
	System.out.println("ia4.name->"+i.getHostName());
}

URL

url주소를 이용하여 코드 긁어오기

URL url = new URL("https://www.seoul.go.kr/main/index.jsp");
// URLConnection객체를 통해 헤더정보를 얻어올 수 있다.
URLConnection connection = url.openConnection();
connection.connect(); //채널을 확보하여 헤더정보 가져오기
String header = connection.getContentType(); 
String encode = header.substring(header.indexOf("=")+1); // UTF-8, euc-kr -> 한글 타입

//코드 긁어오기
InputStream is = url.openStream(); //byte단위
InputStreamReader isr = new InputStreamReader(is, encode); //문자단위
BufferedReader br = new BufferedReader(isr); //한줄씩

File f = new File("c://testFolder/seoul.html");
FileWriter fos = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fos);
			
String inData = " ";
while((inData = br.readLine()) != null) {
	System.out.println(inData);
	bw.write(inData+"\n");
}
profile
터벅터벅 개발자 지망생의 하루

0개의 댓글