들어가기에 앞서, PrintWriter 는 Reader가 없는 오직 출력을 위한 객체입니다.

사용 빈도가 다른 Reader들에 비해 높다고 하니, 꼭 참고 하시기 바랍니다!

아래 예제는 쓰는 방법에 대해서만 설명하였으니, 응용하는 방법은 뒤에서 더 자세히 다루겠습니다.

 

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Ex01PrintWriter {

 public static void main(String[] args) throws IOException {
  
  //PrintWriter writer = new PrintWriter(System.out,true); // Auto flush 기능
  
  PrintWriter writer = new PrintWriter(new FileWriter("/home/pc36/io/print.txt"),true); // Auto flush 기능 및 파일이 출력될 경로 지정
  
  writer.println(">>> 개인 정보 출력 <<<");
  
  writer.printf("%s, %d, %c, %s\n", "이름1", 25, 'M', "010-1234-5678");
  writer.printf("%s, %d, %c, %s\n", "이름2", 25, 'F', "010-4567-8910");
  writer.printf("%s, %d, %c, %s\n", "이름3", 35, 'M', "010-1845-9541");
  
  // writer.flush(); => Auto flush 가 true이므로 따로 입력해주지 않아도 됩니다.
  
  System.out.println("데이터 출력 완료.");  
 }
}

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Ex01ByteToChar {

 public static void main(String[] args) throws IOException {
  
  InputStreamReader reader = null;
  OutputStreamWriter writer = null;
  
  // 키보드로부터 문자 입력 받은 후 파일에 기록, (경로 지정)
  File file = new File("/home/pc36/io/memo.txt");
  
  reader = new InputStreamReader(System.in);
  writer = new OutputStreamWriter(new FileOutputStream(file));
  
  System.out.println(">>>> 메모를 남겨주세요. <<<<");
  
  char[] cbuf = new char[256]; // byte를 Char형처럼
  
  while(true) {
   int len = reader.read(cbuf); // CTRL+D(리눅스 기준)
   if(len == -1) {
    System.out.println("키보드 연결을 해제합니다.");
    break;
   }
   writer.write(cbuf,0,len);
  }
  writer.flush();
  
  System.out.println(">>>> 메세지 저장 완료. <<<<");
  
  writer.close();
 }
}

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Ex02File {

 public static void main(String[] args) throws IOException {
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
  
  String today = dateFormat.format(new Date());
  
  File parent = new File("/home/pc36/io", today);
  // File parent = new File("/usr/lib/io", today); // 디렉토리 생성 실패의 경우(권한이 없을 때)
  
  if(parent.exists()) {
   System.out.println("해당 디렉터리가 존재합니다.");
  }else {
   System.out.println("해당 디렉터리가 존재하지 않습니다.");
   
   if(parent.mkdirs()) {
    System.out.println(parent.getPath() + " 디렉터리 생성 완료.");
   }else {
    System.out.println(parent.getPath() + " 디렉터리 생성 실패.");
   }
  }
  
  // 파일 만들기
  File file = new File(parent, "sample2.txt");
  
  if(file.exists()) {
   System.out.println("해당 파일이 존재합니다.");
  }else {
   System.out.println("해당 파일이 존재하지 않습니다.");
   
   if(file.createNewFile()) {
    System.out.println(file.getPath() + " 파일 생성 성공");
   }
   file.setReadOnly(); // 읽기 전용
  }
 }
}

 

#자바 #File #SimpleDateFormat

 

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

public class Ex01File {

 public static void main(String[] args) throws IOException {
  
  
 /*
  File file = new File("/home/pc36/io/sample.txt");
  File file = new File("../sample.txt");
  
  System.out.println("getName() : " + file.getName());
  System.out.println("getAbsolutePath() : " + file.getAbsolutePath());
  System.out.println("getCanonicalPath() : " + file.getCanonicalPath());
  System.out.println("getPath() : " + file.getPath());
  System.out.println("getParent() : " + file.getParent());
 */
  
  // 루트 디렉토리 목록 가져오기, 윈도우는 드라이브라는 개념을 사용하여 루트 디렉토리가 여러개다.
  // 윈도우 외에 루트 디렉토리는 하나(/)다.
  
  File[] roots = File.listRoots();
  // System.out.println(roots[0]);
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy년 MM월 dd일 (E) HH:mm:ss");
  
  for(int i=0; i<roots.length; i++) {
   File root = roots[i];
   File[] files = root.listFiles(); // 하위 디렉토리, 파일 목록
   
   for(File file : files) {
    // 수정일자, 유형, 파일 크기, 파일명
    System.out.printf("%s\t %s\t %s\t %s\n",
        dateFormat.format(file.lastModified()),
        file.isDirectory() ? "<DIR>" : "   ",
        (file.length()/1024) + "KB",
        file.getName()
        );
   }
  }
 }
}

 

/* 함수적 인터페이스(@FunctionalInterface)
  람다식이 하나의 메서드를 정의하기 때문에 두 개 이상의 추상 메서드를 가질 수 없다.
  하나의 추상 메서드가 선언된 인터페이스를 함수적 인터페이스(functional interface)라고
  한다.
  @FunctionalInterface 어노테이션을 붙여 사용한다. */


/* Runnable interface => FunctionalInterface */
// 익명 중첩 클래스 내에서 람다식 사용이 가능하다.

public class Ex01Lambda {

 public static void main(String[] args) {
  
  // 기존 방식
  // Thread t1 = new Thread(Runnable target)
  Thread t1 = new Thread(new Runnable() {

   @Override
   public void run() {
    System.out.println("기존 익명 중첩 클래스 방식");
   }
   
  });
  
  t1.start();
  
  // 람다식(JAVA 1.8~)
  // Thread t3 = new Thread(()-> System.out.println("람다식 방식"));
  Thread t2 = new Thread(()->{ // 한 줄이면 블럭({})을 쌓지 않아도 된다.
   System.out.println("람다식 방식");
     });
  
  
  t2.start();
 }
}

 

#자바컬렉션 #리스트 #ArrayList

 

// Vetctor (동기화 보장), ArrayList(동기화 보장 X)

import java.util.ArrayList;

public class Ex01ArrayList {

 public static void main(String[] args) {
  
  // ArrayList<E> => <E> = Generic(일반화), 타입을 결정하지 않는다.
  // ex) ArrayList<String> => 오직 String 타입만 받는다. 잘못된 데이터가 들어오는 것을 방지한다.
  
  // ArrayList list = new ArrayList(); // 오직 객체(레퍼런스) 타입만 받는다.
  // 자바 1.5 버전 이후부터 <E>(GENERIC) 사용 가능
  ArrayList<String> list = new ArrayList<String>(); // 오직 String 타입만 받는다.
  
  list.add("가");
  list.add("나");
  list.add(new String("다"));
  list.add(new String("라"));
  
  // list.add(new Integer(50));
  
  System.out.println(list); // 순서의 개념이 존재.
  
  list.add("나");
  System.out.println(list); // 데이터의 중복이 가능하다.
  
  if(list.contains("다")) { // 존재 여부
   // System.out.println("존재합니다.");
  }else {
   // System.out.println("존재하지 않습니다.");
  }
  
  
  if(list != null && !list.isEmpty()) { // list가 null이 아니고 list가 비어있지 않아야함.
   int size = list.size(); // 메서드를 직접 호출하는 것보다 변수로 설정하여 호출하는 것이 좋다.
   for(int i =0; i<size; i++) { // 데이터 순차 접근
    //  String name = (String)list.get(i);
    String name = list.get(i); // 형 변환을 하지 않아도 된다.
    System.out.println(name);
    
   }
  }
  System.out.println("====================");
   // Advanced For, forEach
   // 순차 출력의 경우 장점 크다.
   // 자바 1.5 버전 이후부터 <E>(GENERIC) 사용 가능
   for(String name : list) { // list에 담겨있는 값을 하나씩 꺼내 String name에 담는다. 
    System.out.println(name);
   }
  
 }
}

 

 public static void main(String[] args) {
  // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy년 MM월 dd일 a hh시 mm분 ss초 SSS");
  // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd E요일");
  
  Date date = new Date(); // 현재 시간, 표준
  System.out.println("date : " + date);
  
  String strDate = dateFormat.format(date);
  System.out.println("strDate : " + strDate);
 }

 

#year #month #Calendar #BufferedReader #for

 

 public static void main(String[] args) throws NumberFormatException, IOException {
  
  
  
  // 년와 월을 입력 받아 달력을 출력
  BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
  
  System.out.print("년을 입력해주세요 : ");
  int year = Integer.parseInt(read.readLine());
  
  System.out.print("월을 입력해주세요 : ");
  int month = Integer.parseInt(read.readLine());
  
  Calendar cal = Calendar.getInstance(); // 현재 날짜와 시간
  
    // 해당 월의 첫번째 날짜의 요일
    // DAY_OF_WEEK
    cal.set(year, month-1, 1);
    int dayOfweek = cal.get(Calendar.DAY_OF_WEEK)-1; // 1~7 -> 0~6
    // int dayOfweek = (lastYear + leapYear_cnt + dayOfYear)%7;
   
    
    // 월에 따른 날짜 출력 조건
    // getActualMAXIMUM -> 현재 객체의 최대값 반환 / getMAXIMUM -> 전체 중, 최대값만 반환
    int lastday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    
    System.out.printf("                     %d년 %02d월\n", year, month);
    System.out.printf("일\t월\t화\t수\t목\t금\t토\n");
    
    // 공백 출력
    for(int i =0; i<dayOfweek; i++) {
     System.out.print("\t");
    }
    // 날짜 출력
    for(int i = 1; i<=lastday; i++) {
     System.out.print(i + "\t");
     if((dayOfweek+i)%7 ==0) {
      System.out.println();
     }
    }

    
 }

#JAVA SERVER #JAVA CLIENT

#MULTICAST #UNICAST #BROADCAST

#TCP/IP #SOCKET #SERVERSOCKET

 

* 설명 :

( ex. N - 큰 의미, n - 좁은 의미)

1. 브로드캐스트란?(1:N 통신)

   - 데이터를 여러 방향으로 동시에 전송하여 동일 IP그룹에 있는 컴퓨터라면 데이터를 수신할 수 있는 방식이다.

 

2. 멀티캐스트란?(1:n통신)

- 다중의 수신 대상자들에게 보내는 방식이다.

 

3. 유니캐스트란?(1:1 통신)

- 특정한 대상 수신자에게만 보내는 방식이다.

 

 

#1. 클라이언트 단

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;

public class Ex01MulticastClient {

 public static void main(String[] args) {
  
  DatagramPacket packet = null;
  MulticastSocket socket = null;
  
  try {
   socket = new MulticastSocket(9006);
   System.out.println("클라이언트 생성.");
   
   // 그룹에 조인(라우터가 보냄)
   InetAddress address = InetAddress.getByName("224.128.1.5"); // 멀티 캐스트를 위한 아이피 설정
   socket.joinGroup(address);
   
   byte[] buf = new byte[512];
   
   packet = new DatagramPacket(buf, buf.length);
   
   while (true) {
    // 패킷 수신
    socket.receive(packet);

    String msg = new String(packet.getData(), 0, packet.getLength());
    System.out.println("수신 > " + msg);
   }
   
  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


 

#2. 서버 단

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class Ex01MulticastServer {

 public static void main(String[] args) {
  
  DatagramPacket packet = null;
  MulticastSocket socket = null;
  
  try {
   socket = new MulticastSocket();
   System.out.println("서버 생성 성공.");
   
   BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
   
   // IPv4 아래의 내용은 이전의 포스팅을 통해 설명 해두었음.
   // A Class : 0000 (0000) => 0.0.0.0 ~ 127.255.255.255
   // B Class : 1000 (0000) => 128.0.0.0 ~ 191.255.255.255
   // C Class : 1100 (0000) => 192.0.0.0 ~ 223.255.255.255
   // D Class : 1110 (0000) => 224.0.0.0 ~ 239.255.255.255
   // E Class : 1111 (0000) => 240.0.0.0 ~ 255.255.255.255
   InetAddress address = InetAddress.getByName("224.128.1.5"); // 멀티캐스트 방식으로 서버 주소를 설정함.

   
   while(true) {
    System.out.print("입력 : ");
    String msg = reader.readLine();
    
    if(msg==null) {
     break;
    }
    
    packet = new DatagramPacket(msg.getBytes(), msg.getBytes().length, address, 9006);
    
    socket.send(packet);
   }
   
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

// 메서드 오버로딩 : 한 클래스 내에서 같은 이름의 메소드를 중복적으로 정의하는 것


class Calculator {

public int plus(int a, int b) {

return a+b;

}

public int plus(int a, int b, int c) { // 메서드 오버로딩

return a+b+c;

}

public float plus(float a, float b) { // 메서드 오버로딩

return a+b;

}

public int minus(int a, int b) {

return a-b;

}

public int multiple(int a, int b) {

return a*b;

}

public int divide(int a, int b) {

return a/b;

}

}

////////////////////////////////////////////////////////////////////

public static void main(String[] args) {

Calculator calc = new Calculator();

int x = 10;

int y = 20;

int z = calc.plus(x, y);

System.out.println("z = " + z);

float a = calc.plus(3.14F,2.14F);

System.out.println("a = " + a);

}

+ Recent posts