package demo.properties;

import java.io.FileReader;
import java.util.Properties;

public class PropertiesDemo {

	public static void main(String[] args) throws Exception {
		Properties prop = new Properties();

		FileReader reader = new FileReader("src/demo/properties/config.properties");
		
		// void load(Reader reader)
		// FileReader객체를 사용해서 파일의 정보를 읽어온다.
		prop.load(reader);
		
		// String getProperty(String key)
		// 프로퍼티 파일에서 지정된 키값으로 설정된 값을 반환한다.
		String value1 = prop.getProperty("user.name");
		System.out.println(value1);
		
		String value4 = prop.getProperty("select.users");
		System.out.println(value4);
	}
}
package demo.etc;

import java.util.LinkedList;

public class QueueDemo {

	public static void main(String[] args) {
		LinkedList<String> queue = new LinkedList<String>();
		
		queue.offer("홍길동");		
		queue.offer("김유신");		
		queue.offer("강감찬");		
		queue.offer("이순신");
		
		String value1 = queue.poll();
		System.out.println(value1);
		System.out.println("현재 개수 : " + queue.size());
		
		String value2 = queue.poll();
		System.out.println(value2);
		System.out.println("현재 개수 : " + queue.size());

	}
}
package demo.etc;

import java.util.Stack;

public class StackDemo {

	public static void main(String[] args) {
		
		Stack<String> stack = new Stack<String>();
		
		stack.push("홍길동");
		stack.push("김유신");
		stack.push("강감찬");
		stack.push("이순신");
		
		String value1 = stack.pop();
		System.out.println(value1);
		System.out.println("현재 개수 : " + stack.size());
		
		String value2 = stack.pop();
		System.out.println(value2);
		System.out.println("현재 개수 : " + stack.size());

	}
}

'자바 > collection' 카테고리의 다른 글

sort  (0) 2019.06.10
set  (0) 2019.06.10
map  (0) 2019.06.10
list  (0) 2019.06.10
package demo.sort;

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListDemo1 {

	public static void main(String[] args) {
		ArrayList<User> users = new ArrayList<User>();
		users.add(new User(10, "김유신"));
		users.add(new User(80, "이순신"));
		users.add(new User(40, "유관순"));
		users.add(new User(50, "홍길동"));
		users.add(new User(20, "강감찬"));
		
		Collections.sort(users);
		
		for (User user : users) {
			System.out.println(user.getNo() + ", " + user.getName());
		}
	}
}
package demo.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListDemo2 {

	public static void main(String[] args) {
		ArrayList<Fruit> box = new ArrayList<Fruit>();
		box.add(new Fruit("사과", 2000));
		box.add(new Fruit("바나나", 6000));
		box.add(new Fruit("오렌지", 3000));
		box.add(new Fruit("아보카도", 8000));
		box.add(new Fruit("토마토", 4000));
		box.add(new Fruit("감", 9000));
		
		Comparator<Fruit> priceComparator = new Comparator<Fruit>() {
			@Override
			public int compare(Fruit o1, Fruit o2) {
				return o1.getPrice() - o2.getPrice();
			}
		};
		
		Collections.sort(box, priceComparator);
		
		for (Fruit fruit : box) {
			System.out.println(fruit.getName() + " " + fruit.getPrice());
		}
	}
}
package demo.sort;

import java.util.TreeSet;

public class TreeSetDemo {

	public static void main(String[] args) {
		TreeSet<User> users = new TreeSet<User>();
		
		users.add(new User(10, "김유신"));
		users.add(new User(80, "이순신"));
		users.add(new User(40, "유관순"));
		users.add(new User(50, "홍길동"));
		users.add(new User(20, "강감찬"));
		
		for (User user : users) {
			System.out.println(user.getNo() + ", " + user.getName());
		}		
	}
}
package demo.sort;

public class User implements Comparable<User>{

	private int no;
	private String name;
	
	public User() {}
	public User(int no, String name) {
		this.no = no;
		this.name = name;
	}

	public int getNo() {
		return no;
	}
	
	public void setNo(int no) {
		this.no = no;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public int compareTo(User o) {
		return name.compareTo(o.name);
	}
    
}
package demo.sort;

public class Fruit {

	private String name;
	private int price;
	
	public Fruit() {}
	public Fruit(String name, int price) {
		this.name = name;
		this.price = price;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getPrice() {
		return price;
	}
	
	public void setPrice(int price) {
		this.price = price;
	}
}

'자바 > collection' 카테고리의 다른 글

properties, queue, stack  (0) 2019.06.10
set  (0) 2019.06.10
map  (0) 2019.06.10
list  (0) 2019.06.10
package demo.set;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetDemo1 {

	public static void main(String[] args) {
		HashSet<String> names = new HashSet<String>();
		
		names.add("홍길동");
		names.add("김유신");
		names.add("강감찬");
		names.add("홍길동");
		names.add("이순신");
		names.add("유관순");
		
		Iterator<String> it = names.iterator();
		while (it.hasNext()) {
			String name = it.next();
			System.out.println(name);
		}
		System.out.println();
		names.clear();
		
		System.out.println("비어 있는가? " + names.isEmpty());
		System.out.println("저장된 개수 : " + names.size());
		
		for (String name : names) {
			System.out.println(name);
			
		}
	}
}
package demo.set;

import java.util.HashSet;

public class HashSetDemo2 {

	public static void main(String[] args) {
		
		// Contact에서 hashCode()와 equals() 메소드를 재정의해서
		// 객체가 달라도 번호가 동일하면 동일한 객체로 간주하도록 만들었다.
		
		Contact contact1 = new Contact(10, "홍길동", "010-1111-1111");
		Contact contact2 = new Contact(20, "김유신", "010-2222-1111");
		Contact contact3 = new Contact(10, "홍길동", "010-1111-1111");
		Contact contact4 = new Contact(40, "이순신", "010-4444-1111");
		
		HashSet<Contact> contacts = new HashSet<Contact>();
		contacts.add(contact1);
		contacts.add(contact2);
		contacts.add(contact3);
		contacts.add(contact4);
		contacts.add(contact1);
		contacts.add(contact2);

		System.out.println(contacts);
	}
}
package demo.set;

import java.util.TreeSet;

public class TreeSetDemo {

	public static void main(String[] args) {
		TreeSet<String> names = new TreeSet<String>();
		
		names.add("이순신");
		names.add("김유신");
		names.add("강감찬");
		names.add("홍길동");
		names.add("유관순");
		names.add("김구");
		
		for (String name : names) {
			System.out.println(name);
		}
	}
}
package demo.set;

import java.util.Random;
import java.util.TreeSet;

public class TreeSetDemo2 {

	public static void main(String[] args) {
		TreeSet<Integer> lotto = new TreeSet<Integer>();
		Random random = new Random();
		
		while (true) {
			int number = random.nextInt(45) + 1;
			lotto.add(number);
			
			if (lotto.size() == 6) {
				break;
			}
		}
		System.out.println(lotto);
	}
}
package demo.set;

public class Contact {

	private int no;
	private String name;
	private String tel;
	
	public Contact() {}

	public Contact(int no, String name, String tel) {
		super();
		this.no = no;
		this.name = name;
		this.tel = tel;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	@Override
	public String toString() {
		return "Contact [no=" + no + ", name=" + name + ", tel=" + tel + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + no;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Contact other = (Contact) obj;
		if (no != other.no)
			return false;
		return true;
	}
	
}

'자바 > collection' 카테고리의 다른 글

properties, queue, stack  (0) 2019.06.10
sort  (0) 2019.06.10
map  (0) 2019.06.10
list  (0) 2019.06.10
package demo.map;

import java.util.HashMap;

public class HashMapDemo1 {

	public static void main(String[] args) {
		
		HashMap<Integer, String> map = new HashMap<Integer, String>();
		
		// put(K key, V value)
		// Map객체에 키, 값, 쌍으로 저장하기
		map.put(100, "홍길동");
		map.put(101, "김유신");
		map.put(102, "강감찬");
		map.put(103, "이순신");
		
		// V get(Object key)
		// Map객체에서 지정된 키에 해당하는 값 꺼내기
		String value1 = map.get(101);
		System.out.println(value1);
		
		// V remove(Object key)
		// Map객체에서 지정된 키에 해당하는 값을 반환하고 삭제하기
		map.remove(102);
		
		boolean empty = map.isEmpty();
		System.out.println("비어 있는가? " + empty);
		
		int len = map.size();
		System.out.println("저장된 개수: " + len);
		map.clear();
		System.out.println(map);
	}
}
package demo.map;

import java.util.HashMap;
import java.util.HashSet;

public class HashMapDemo2 {

	public static void main(String[] args) {
		
		HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
		
		HashSet<String> team1 = new HashSet<String>();
		team1.add("바다");
		team1.add("유진");
		team1.add("슈");
		
		HashSet<String> team2 = new HashSet<String>();
		team2.add("솔라");
		team2.add("문별");
		team2.add("화사");
		team2.add("휘인");

		HashSet<String> team3 = new HashSet<String>();
		team3.add("웬디");
		team3.add("아이린");
		team3.add("슬기");
		team3.add("조이");
		team3.add("예리");
		
		map.put("SES", team1);
		map.put("마마무", team2);
		map.put("레드벨벳", team3);
		
		HashSet<String> names = map.get("마마무");
		for (String name : names) {
			System.err.println(name);
		}
	}
}

'자바 > collection' 카테고리의 다른 글

properties, queue, stack  (0) 2019.06.10
sort  (0) 2019.06.10
set  (0) 2019.06.10
list  (0) 2019.06.10
package demo.list;

import java.util.ArrayList;

public class ArrayListDemo1 {

	public static void main(String[] args) {
		
		ArrayList<String> names = new ArrayList<String>();
		
		// 객체 저장하기
		// boolean add(E e)
		names.add("홍길동");     //names[0] = "홍길동";
		names.add("김유신");     //names[1] = "김유신";
		names.add("강감찬");     //names[2] = "강감찬";
		names.add("이순신");     //names[3] = "이순신";
		names.add("유관순");     //names[4] = "유관순";
		names.add("유관순");     //names[4] = "유관순";
		names.add("유관순");     //names[4] = "유관순";

		System.out.println(names);
		
		// 지정된 위치의 객체 삭제
		// E remove(int index)
		names.remove(2); // 강감찬 삭제
		
		// 지정된 객체를 삭제
		// boolean remove(Object o)
		names.remove("유관순"); 	// 유관순 삭제
		
		// 지정된 인덱스에 저장된 객체 꺼내기
		// E get(int index)
		String value1 = names.get(0);
		System.out.println("0번째 저장된 객체: " + value1);
		
		
		
		
		// ArrayList에 저장된 모든 객체 꺼내기
		// enhanced for문 사용
		for (String x : names) {
			System.out.println(x);
		}

		// int size()
		// 저장된 객체의 개수를 반환
		int len = names.size();
		System.out.println("저장된 객체의 개수: " + len);
		
		// void clear()
		// 저장된 객체 전체 삭제
		names.clear();
		
		// boolean isEmpty()
		boolean empty = names.isEmpty();
		System.out.println("비어있는가? " + empty);	
	}	
}
package demo.list;

import java.util.ArrayList;

public class ArrayListDemo2 {

	public static void main(String[] args) {
		
		// 기본 자료형을 저장하는 ArrayList
		// 기본 자료형을 저장할 때는 제네릭 타입을 Wrapper 클래스 타입으로 지정한다.
		// int --> Integer, double --> Double, long --> Long, ...
		
		ArrayList<Integer> numbers = new ArrayList<Integer>();
		numbers.add(new Integer(20));
		numbers.add(40); 		// 오토 박싱 --> numbers.add(new Integer(40))
		
		for (Integer x : numbers) {
			System.out.println(x);
		}
		
		for (int x : numbers) {
			System.out.println(x);
		}
		
		ArrayList<Double> scores = new ArrayList<Double>();
	}
}
package demo.list;

import java.util.ArrayList;

public class ArrayListDemo3 {

	public static void main(String[] args) {
		
		// 객체를 저장하는 ArrayList
		ArrayList<Book> books = new ArrayList<Book>();
		
		Book book1 = new Book(100, "이것이 자바다", "신용권", "한빛미디어", 30000);
		Book book2 = new Book(200, "데이터베이스 개론", "홍길동", "한빛미디어", 29000);
		Book book3 = new Book(300, "자바 디자인 패턴", "켄트벡", "인사이트", 32000);
		Book book4 = new Book(400, "인사이트 자바스크립트", "김유신", "한빛미디어", 27000);
		
		books.add(book1);
		books.add(book2);
		books.add(book3);
		books.add(book4);
		books.add(new Book(500, "스프링 3.0", "이일민", "에이콘출판사", 75000));
		
		System.out.println(books);

		int total = 0;
		for (Book book : books) {
			System.out.println("제목 : " + book.getTitle());
			System.out.println("가격 : " + book.getPrice());
		
			total += book.getPrice();
		}
		System.out.println("전체 가격 : " + total);
	}
}
package demo.list;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListDemo4 {

	public static void main(String[] args) {
		
		ArrayList<String> names = new ArrayList<String>();
		names.add("홍길동");
		names.add("김유신");
		names.add("강감찬");
		names.add("이순신");
		names.add("이성계");
		names.add("김구");
		names.add("김좌진");
		
		for (String name : names) {
			System.out.println(name);			
		}
        
		System.out.println();
		
		for (int i=0; i<names.size(); i++) {
			String name = names.get(i);
			System.out.println(name);
		}
		System.out.println();
		
		/*
		 * Iterator<E>
		 *        콜렉션(List 및 Set)의 요소를 추출, 삭제할 때 사용되는 객체다.
		 *        주요 메소드
		 *        boolean hasNext()     - 추출할 객체가 남아있으면 true를 반환한다.
		 *        E          next()     - 객체를 하나 꺼내서 반환한다.
		 *        void     remove()     - 객체를 삭제한다.
		 */
		
		Iterator<String> it = names.iterator();
		while (it.hasNext()) {
			String name = it.next();
			System.out.println(name);
			if (name.startsWith("김")) {
				it.remove();
			}
		}
		System.out.println(names);
	}
}
package demo.list;

public class Book {
		
	private int no;
	private String title;
	private String author;
	private String publisher;
	private int price;

	public Book() {}

	public Book(int no, String title, String author, String publisher, int price) {
		super();
		this.no = no;
		this.title = title;
		this.author = author;
		this.publisher = publisher;
		this.price = price;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getPublisher() {
		return publisher;
	}

	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Book [no=" + no + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", price="
				+ price + "]";
	}		
}

 

'자바 > collection' 카테고리의 다른 글

properties, queue, stack  (0) 2019.06.10
sort  (0) 2019.06.10
set  (0) 2019.06.10
map  (0) 2019.06.10
package Demo4;

public class Animal {

}
package Demo4;

public class Cat extends Animal {

}
package Demo4;

public class Dog extends Animal {	

}
package Demo4;

public class AnimalApp {

	public static void main(String[] args) {
		Animal a = new Dog();
		Animal b = new Cat();

		Dog c = (Dog) a;
		Cat d = (Cat) b;
		
		Dog e = (Dog) b; // 형 변환 예외 발생
		
	}
}

'자바 > exception' 카테고리의 다른 글

demo3  (0) 2019.06.10
demo2  (0) 2019.06.10
demo1  (0) 2019.06.10
package Demo3;

public class RuntimeExceptionDemo1 {

	public static void stringToUpper(String str) {
		if (str != null) {
			System.out.println(str.toUpperCase());
		}
	}
	
	
	
	public static void main(String[] args) {
		// NullPointException
		// 객체를 참조하지 않는 참조변수(null값을 가지는 참조변수)로
		// 객체의 속성이나 기능을 사용할 때 발생되는 예외다.
		
		String text = null;
		//System.out.println(text.length());
		
		RuntimeExceptionDemo1.stringToUpper(text);
		
	}
}
package Demo3;

public class RuntimeExceptionDemo2 {
	
	public static void main(String[] args) {
		
		// ArrayIndexOutOfBoundException : 배열의 인덱스 범위를 벗어났을 때 발생
		// StringIndexOutOfBoundsException : 문자열의 인덱스범위를 벗어났을 때 발생
		
		String[] names = {"김유신", "강감찬", "이순신"};
		// System.out.println(names[3]);
		
		String text = "abc";
		String subText = text.substring(2, 4);
	}
}
package Demo3;

public class RuntimeExceptionDemo3 {

	public static void main(String[] args) {
		// NumberformatException : 문자열을 숫자로 바꿀 때 숫자로 변환할 수 없는 문자열이 포함되어 있으면 발생
		// int Integer.parseInt(String numberText)
		// double double.parseDouble(String numberText)
		
		String text1 = "1234";
		int number1 = Integer.parseInt(text1);
		System.out.println(number1 * 3);
		
		String text2 = "1234a";
		String text3 = " 1234";
		
		int number2 = Integer.parseInt(text2);
		System.out.println(number2 * 3);
	}
}
package Demo3;

import java.util.Scanner;

public class RuntimeExceptionDemo4 {

	public static void main(String[] args) {
	
		Scanner scanner = new Scanner(System.in);
				
		System.out.println("몸무게 입력> ");
		String value1 = scanner.next();

		System.out.println("키 입력> ");
		String value2 = scanner.next();

		double weight = Double.parseDouble(value1);
		double height = Double.parseDouble(value2)/100;

		double bmi = weight / (height + height);
		System.out.println("bmi 지수 : " + bmi);
		
		if(bmi > 35) {
			System.out.println("고도 비만");
		} else if (bmi > 30) {
			System.out.println("중등도 비만");
		} else if (bmi > 25) {
			System.out.println("경도 비만");
		} else if (bmi > 23) {
			System.out.println("과체중");
		} else if (bmi > 18.5) {
			System.out.println("저체중");
		}
		
		scanner.close();
	}
}
package Demo3;

public class RuntimeExceptionDemo5 {

	public static void main(String[] args) {
		
		String text = "dddd";
		
		int value = StringUtils.stringToInt(text);
		System.out.println("숫자값 : " + value);
	}
}
package Demo3;

public class RuntimeExceptionDemo6 {

	public static void main(String[] args) {
		
		// arithmaic Excpetion 0으로 어떤 수를 나눌 때	}

		System.out.println(3/0);
	}
}
package Demo3;

public class StringUtils {

	public static int stringToInt(String text) {
		int value;
		try {
			value = Integer.parseInt(text);
			
		} catch (NumberFormatException e) {
			value = 0;
		}
		return value;
	}
}

 

'자바 > exception' 카테고리의 다른 글

demo4  (0) 2019.06.10
demo2  (0) 2019.06.10
demo1  (0) 2019.06.10
package Demo2;

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

public class ExceptionDemo1 {

	public static void main(String[] args) {
		
		// 예외 정보 얻기, 출력하기
		try {
			FileWriter writer = new FileWriter("c:/sample.txt");
			writer.write("예외정보 얻기");
			writer.flush();
			writer.close();
		} catch (IOException e) {
			System.out.println("예외 발생!");
			String message = e.getMessage();
			System.out.println("예외 정보 : " + message);
			
			String text = e.toString();
			System.out.println("예외 정보 : " + text);
			
			e.printStackTrace();
		}
	}
}
package Demo2;

public class MyexceptionDemo1 {
	/**
	 * 문자열 배열을 전달받아서 화면에 배열의 내용을 출력하는 메소드
	 * @param names 문자열 배열
	 * @throws MyException 배열이 null이거나 배열의 길이가 0인 경우 예외 발생
	 */
	// 사용자정의 일반예외 <-- Exception 클래스를 상속받으면 일반예외가 된다.
	// 일반예외는 예외처리가 필수다.
	public static void printArray(String[] names) throws MyException {
		if (names == null || names.length == 0) {	// 예외 상황
			throw new MyException("null인 배열이 전달되었습니다.");
		}
		for (String item : names) {
			System.out.println(item);
		}
	}
	public static void main(String[] args) {
		
		String[] teamNames = {"영업팀", "서울팀", "경기팀"};
		String[] studentNames = null;
		try {
			MyexceptionDemo1.printArray(teamNames);
			MyexceptionDemo1.printArray(studentNames);

		} catch (MyException e) {
			e.printStackTrace();
		}
	}
}
package Demo2;

public class MyException extends Exception {
	public MyException() {
		
	}
	
	public MyException(String message) {
		super(message); 			// 예외 정보로 저장된다(Exception의 생성자 호출).
		
	}
}
package Demo2;

// 사용자정의 실행예외 <-- RuntimeException을 상속받으면 실행예외가 된다.
// 실행예외는 예외처리가 선택이다.
public class MyRuntimeException extends RuntimeException {

	public MyRuntimeException() {
		
	}
	
	public MyRuntimeException(String message) {
		super(message);
	}
}
package Demo2;

public class MyRuntimeExceptionDemo1 {

	public static void printArray(String[] items) {
		if (items == null || items.length == 0) {
			throw new MyRuntimeException("배열이 null이거나 길이가 0입니다.");
		}
		
		for (String item : items) {
			System.out.println(item);
		}
	}
	
	public static void main(String[] args) {
		String[] teamNames = {"영업팀", "서울팀", "경기팀"};
		String[] studentNames = null;
		
		MyRuntimeExceptionDemo1.printArray(teamNames);
		MyRuntimeExceptionDemo1.printArray(studentNames);
	}
}

'자바 > exception' 카테고리의 다른 글

demo4  (0) 2019.06.10
demo3  (0) 2019.06.10
demo1  (0) 2019.06.10
package Demo1;

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

public class ExceptionDemo1 {
	
	public static void main(String[] args) {
		// 일반 예외가 발생하는 경우 예외 처리하기
		try {
		System.out.println("try 블록의 수행문 시작");
		FileWriter writer = new FileWriter("sample.txt");
		writer.write("연습");
		writer.flush();
		writer.close();
		System.out.println("try 블록의 수행문 종료");
		} catch (IOException e) {
			System.out.println("파일 생성 혹은 파일 기록 중 오류가 발생하였습니다.");
			System.out.println(e);
			System.out.println("catch 블록의 수행문");
		
		} finally {
			System.out.println("finally 블록의 수행문");
		}
	}
}
package Demo1;

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

public class ExceptionDemo2 {

	public static void main(String[] args) throws IOException {
		
		FileWriter writer = new FileWriter("sample.txt");
		writer.write("연습");
		writer.flush();
		writer.close();
	}
}
package Demo1;

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

public class ExceptionDemo3 {

	public static void method1() throws IOException {
		FileWriter writer = new FileWriter("sample.txt");
		writer.write("예외 떠넘기기");
		writer.flush();	
		writer.close();
	}
	public static void method2() throws ClassNotFoundException {
		Class.forName("demo1.ExceptionDemo1");	// demo1.ExcpetionDemo1 설계도를 메모리에 로딩시킨다.
	}
	
	// 메소드1과 2가 처리를 위임한 예외를 다시 떠넘긴다.
	public static void method3() throws IOException, ClassNotFoundException {
		ExceptionDemo3.method1();
		ExceptionDemo3.method2();
	}
	//메소드 1과 2가 처리를 위임한 예외를 try ~ catch로 처리한다.
	public static void method4() {
		try {
			ExceptionDemo3.method1();
			ExceptionDemo3.method2();
			
		}
		catch (IOException e) {
			
		} catch (ClassNotFoundException e) {
			
		}
	}
	
	
	//메소드 1과 2가 처리를 위임한 예외를 try ~ catch로 처리한다.
	public static void method5() {
		try {
			ExceptionDemo3.method1();
			ExceptionDemo3.method2();
			
		}
		catch (IOException | ClassNotFoundException e) {
			
		} 
	}


	
	//메소드 1과 2가 처리를 위임한 예외를 try ~ catch로 처리한다.
	public static void method6() {
		try {
			ExceptionDemo3.method1();
			ExceptionDemo3.method2();
			
		}
		catch (Exception e) {	// Exception 타입의 변수로 선언하면 try블록에서 발생되는 모든 예외를
								// 캐치할 수 있다.				
		} 
	}

	public static void method7() {
		try {
			ExceptionDemo3.method1();
			ExceptionDemo3.method2();
			
			
		} catch (ClassNotFoundException e) {
			
		} catch (IOException e) {
		} catch (Exception e) {
		}	// 마지막 catch에서는 Exception 타입의 변수로 선언함으로써 미처 예상하지 못했던 예외도 캐치를 할 수 있도록 한다.
	}

	
	public static void main(String[] args) {
		
	}
}
package Demo1;

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

public class exceptionDemo4 {
	public static void method1() {
		 try {
			 FileWriter writer = new FileWriter("sample.txt");
			 writer.write("예외바꾸기");
			 writer.flush();
			 writer.close();
			 
		 } catch (IOException e) {
			 
		 }
	}
	
	public static void method2() {
		
	}
	
	public static void main(String[] args) {
		
	}
}
package Demo1;

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

public class HTAException extends Exception {
	public static void method1() throws HTAException {
		try {
			FileWriter writer = new FileWriter("sample.txt");
			writer.write("예외바꾸기");
			writer.flush();
			writer.close();
		} catch (IOException e) {
			throw new HTAException();	// throw 예외 발생 시키기
		}
	}
	public static void method2() throws HTAException {	// 3. 2번에서 발생시킨 예외를 떠넘긴다.
		try {
			Class.forName("demo1.HTAException");
			
		} catch (ClassNotFoundException e) {	// 1. try 블록에서 발생한 예외를 캐치
			throw new HTAException();			// 2. HTAException 예외를 생성해서 발생시킴
		}
	}
	
	public static void main(String[] args) {
		try {
			method1();
			method2();
		} catch (HTAException e) {	// 4. 처리를 위임받는 예외의 종류가 HTAException 으로 줄어들게 된다.
		}
	}
}

 

'자바 > exception' 카테고리의 다른 글

demo4  (0) 2019.06.10
demo3  (0) 2019.06.10
demo2  (0) 2019.06.10
package Demo5;

public class MathDemo {

	public static void main(String[] args) {
		
		double result1 = Math.ceil(3.1);
		double result2 = Math.ceil(3.0);
		double result3 = Math.ceil(3.9);
		System.out.println(result1);
		System.out.println(result2);
		System.out.println(result3);
		
		double result4 = Math.floor(3.1);
		double result5 = Math.floor(3.0);
		double result6 = Math.floor(3.9);
		System.out.println(result4);
		System.out.println(result5);
		System.out.println(result6);
		
		double result7 = Math.round(3.1);
		double result8 = Math.round(3.0);
		double result9 = Math.round(3.9);
		System.out.println(result7);
		System.out.println(result8);
		System.out.println(result9);
		
	}
}
package Demo4;

import java.util.Date;

public class DateDemo {

	public static void main(String[] args) {
		// 컴퓨터 현재 날짜 및 시간 정보를 갖고 있는 Date객체가 생성된다.
		Date now = new Date();
		java.sql.Date x = null;
		
		System.out.println(now);
		System.out.println(now.toString()); // 날짜와 시간정보를 문자열로 제공하도록 재정의
		
		long value = now.getTime(); // UNIX타임
		System.out.println(value);
		
		now.setTime(1234567890123L);
		System.out.println(now);
		
	}
}
package Demo4;

import java.util.Random;

public class RandomeDemo {
	public static void main(String[] args) {
	
		// 난수를 발생시키는 Random객체 생성
		Random random = new Random();
		
		// int범위의 최솟값과 최댓값 사이의 임의의 정수를 제공
		int num1 = random.nextInt();
		System.out.println(num1);
		
		// 0 <= 난수 < 100
		int num2 = random.nextInt(100);
		System.out.println(num2);

		int num3 = random.nextInt(6) + 1;
		System.out.println(num3);
	}
}
package Demo4;

import java.util.Arrays;

public class ArraysDemo {
	public static void main(String[] args) {
		
		int[] scores = {10, 30, 1, 7, 31, 46, 5};
		Arrays.sort(scores);
		
		System.out.println(Arrays.toString(scores));
		
		String[] names = {"홍길동", "이순신", "강감찬", "김유신", "유관순", "김구"};
		Arrays.parallelSort(names);
		System.out.println(Arrays.toString(names));
	}
}
package Demo4;

public class StringBuilderDemo {

	public static void main(String[] args) {
		
		String title = "이것이 자바다";
		String writer = "신용권";
		int price = 30000;
		
		String text = "제목 : " + title + ", 저자 : " + writer + ", 가격 : " + price;
		System.out.println(text);
		StringBuilder sb = new StringBuilder();
		
		sb.append("제목 : ");
		sb.append(title);
		sb.append(", 저자 : ");
		sb.append(writer);
		sb.append(", 가격 : ");
		sb.append(price);
		
		String text2 = sb.toString();
		System.out.println(text2);
	}
}
package Demo4;

import java.util.StringTokenizer;
public class StringTokenizerDemo {
	public static void main(String[] args) {
		StringTokenizer st = new StringTokenizer("김유신 강감찬 이순신 홍길동");
		
		int count = st.countTokens();
		System.out.println("토큰 개수 : " + count);
		
		boolean b1 = st.hasMoreTokens();
		System.out.println("토큰이 남아 있나? " + b1);

		String name1 = st.nextToken();
		System.out.println(name1);
		
		while (st.hasMoreElements()) {
			String name = st.nextToken();
			System.out.println(name);
			
		}
		
		StringTokenizer st2 = new StringTokenizer("100,20,50,28,59,9,17,83", ",");
		int total = 0;
		
		while (st2.hasMoreElements()) {
			int a = Integer.parseInt(st2.nextToken());
			System.out.println(a);
			total+=a;
		}
		
		System.out.println("합계 : " + total);
		
		String text = "홍길동,010-1111-1111,,중앙HTA";
		String[] values = text.split(",");
		StringTokenizer st3 = new StringTokenizer(text,",");
		
		System.out.println("배열의 길이 : " + values.length);
		System.out.println("토큰의 길이 : " + st3.countTokens());		
	}
}
package Demo4;

public class SystemDemo {
public static void main(String[] args) {
	
	long time = System.currentTimeMillis();
	System.out.println(time);
	
	String value1 = System.getProperty("java.version");
	String value2 = System.getProperty("os.name");
	String value3 = System.getProperty("user.name");
	String value4 = System.getProperty("user.home");
	System.out.println("자바버전 : " + value1);
	System.out.println("운영체제이름: " + value2);
	System.out.println("사용자 이름 : " + value3);
	System.out.println("사용자 홈 디렉토리 : " + value4);
	}
}
package Demo4;
import java.util.Properties;
import java.util.Set;

public class SystemDemo2 {
	public static void main(String[] args) {
		Properties prop = System.getProperties();
		// 시스템의 현재 시간 정보 조회하기
		long time = System.currentTimeMillis();
		System.out.println(time);
		
		// 시스템의 속성값 조회하기
		// String System.getProperty(String name)
		Set<Object> keys = prop.keySet();
		for (Object key : keys) {
			String value = prop.getProperty(key.toString());
			System.out.println("[" + key + "]" + value);
		}
		
		// 시스템의 환경변수값 조회
		// String System.getenv(String name)
		String env1 = System.getenv("JAVA_HOME");
		String env2 = System.getenv("Path");
		System.out.println("자바홈: " + env1);
		System.out.println("패스: " + env2);
		
	}
}
package Demo4;

import java.util.Arrays;

public class SystemDemo3 {
	public static void main(String[] args) {
		
		// 배열 복사
		// void System.arraycopy(Object src, int srcPost, Object dest, int destPos, int length)
		// src : 원본배열
		// srcPso : 원본배열의 복사 시작 위치
		// dest : 목적지 배열
		// destPos : 목적지 배열의 데이터 삽입 시작 위치
		// length : 복사할 배열의 아이템 개수
		String[] src = {"사과", "배", "바나나", "토마토", "레몬", "감", "포도", "오렌지", "멜론"};
		String[] dest1 = new String[5];
		String[] dest2 = new String[10];
		
		System.arraycopy(src, 3, dest1, 0, 5);
		System.arraycopy(src, 0, dest2, 4, 6);
		
		System.out.println(Arrays.deepToString(dest1));
		System.out.println(Arrays.deepToString(dest2));
		
	}
}
package Demo4;

public class WrapperDemo1 {

	public static void main(String[] args) {
		Integer num1 = new Integer(30);   // 박싱
		Integer num2 = new Integer("30");
		
		// 정수값 획득 : int intValue()
		int value1 = num1.intValue();    // 언박싱
		int value2 = num2.intValue();
		System.out.println(value1);
		System.out.println(value2);

		
		Double num3 = new Double(3.14);   // 박싱
		Double num4 = new Double("3.14");
		
		
		// 실수값 획득 : double doubleValue()
		double value3 = num3.doubleValue();    //언박싱
		double value4 = num4.doubleValue();
		System.out.println(value3);
		System.out.println(value4);
		
	}
}
package Demo4;

public class WrapperDemo2 {
	public static void main(String[] args) {
		
		// 오토박싱/언박싱
		Integer num1 = 10; 
		Double num2 = 3.14;
	}
}

'자바 > api' 카테고리의 다른 글

demo3  (0) 2019.06.10
demo2  (0) 2019.06.10
demo1  (0) 2019.06.10
package demo3;

public class StringDemo1 {
	public static void main(String[] args) {
		
		String str1 = "hello world";
		// String str1 = new String("hello world");
		
		// String toUpperCase() : 소문자를 대문자로 변환해서 반환한다.
		// String toLowerCase() : 대문자를 소문자로 변환해서 반환한다.

		String result1 = str1.toUpperCase();
		
		System.out.println("원본1 : " + str1);
		System.out.println("결과1 : " + result1);
		System.out.println("결과1 : " + str1.toUpperCase());
		
		String result2 = result1.toLowerCase();
		System.out.println("결과2 : " + result2);
		System.out.println(str1);

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

		
		// String replace(String old, String new) : 해당 글자 모두 바꾸기
		String str2 = "이것이 자바다. 자바 초급자를 위한 안내서";
		String result3 = str2.replace("자바", "파이썬");
		System.out.println("원본2 : " + str2);
		System.out.println("결과3 : " + result3);
		
		// int length() : 문자열의 길이를 반환한다.
		String str3 = "오늘 점심은 어떤거 먹지?";
		int len = str3.length();
		System.out.println("문자열의 길이 : " + len);
		
		
		
		String name1 = new String("이순신");
		String name2 = new String("이순신");
		String name3 = "이순신";
		String name4 = "이순신";
		
		System.out.println(name1 == name2);
		System.out.println(name1.equals(name2));
		System.out.println(name3 == name4);
		System.out.println(name3.equals(name4));		

		// 1. == 주소값 비교
		// 2. equals() 내용 비교
		// equals메소드는 String객체를 생성하는 방법에 상관업이 문자열의 내용이 동일하면
		// true값을 반환. 따라서 문자열의 비교는 반드시 equals()메소드를 사용해야 한다.
	
		
		// String substring(int beginIndex): 끝까지 잘라낸 새로운 문자열을 반환
		//String substring(int beginIndex, int endIndex): ~까지 잘라낸 새로운 문자열을 반환
		String str4 = "이것이 자바다";
		String result5 = str4.substring(1);
		System.out.println("결과5: " + result5);
		
		String result6 = str4.substring(2,6);
		System.out.println("결과6: " + result6);
		
		String str5 = "이것이 자바다";
		boolean result7 = str5.contains("자바");
		System.out.println("결과: "+ result7);
		
		// boolean startsWith(String str) : 지정된 문자열로 시작하는지 여부를 반환한다.
		// boolean endsWith(String str) : 지정된 문자열로 끝나는지 여부를 반환한다.
		String str6 = "http://www.daum.net";
		String str7 = "www.google.com";
		String str8 = "www.naver.com";
		System.out.println("결과8: " + str6.startsWith("http"));
		System.out.println("결과9: " + str6.startsWith("http"));
		System.out.println("결과10: " + str6.startsWith("http"));
		System.out.println("결과11: " + str6.startsWith("com"));
		System.out.println("결과12: " + str6.startsWith("com"));
		System.out.println("결과13: " + str6.startsWith("com"));
		
		// boolean empty(): 문자열이 비어있으면 true를 반환.
		
		String str12 = "     이것이 자바다        ";
		String result17 = str12.trim();
		String str11 = "";
		System.out.println("결과17: " + "[" + result17 + "]");
			
		String str13 = "이것이 자바다. 자바 업무용 추천 도서";
		int result18 = str13.indexOf("자바");
		int result19 = str13.indexOf("파이썬");
		System.out.println("결과18 : " + result18);
		System.out.println("결과19 : " + result19);

		String str14 = "이것이 자바다";
		char result20 = str14.charAt(1);
		System.out.println("결과20: " + result20);

		String str15 = " 이순신, 김유신, 강감찬, 홍길동, 유관순";
		String[] result21 = str15.split(",");
		System.out.println("결과21: " + result21[0]);
		System.out.println("결과21: " + result21[1]);
		System.out.println("결과21: " + result21[2]);
		System.out.println("결과21: " + result21[3]);
		System.out.println("결과21: " + result21[4]);	
	}
}
package demo3;

import java.util.Scanner;

public class StringDemo2 {
public static void main(String[] args) {
	Scanner scanner = new Scanner(System.in);
	
	System.out.print("비밀번호를 입력하세요: ");
	String pwd1 = scanner.next();
	System.out.print("비밀번호를 다시 입력하세요: ");
	String pwd2 = scanner.next();
	
	System.out.println(pwd1 ==pwd2);
	System.out.println(pwd1.contentEquals(pwd2));
	
	// scanner.close();
	}
}
package demo3;

import java.util.Scanner;

public class StringDemo3 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("이메일을 입력하세요: ");
		String email = scanner.next();
		
		int endIndex = email.indexOf("@");
		String id = email.substring(0, endIndex);
		System.out.println("아이디: " + id);
		
		scanner.close();
		}
}
package demo3;

import java.util.Scanner;

public class StringDemo4 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("이름,국어,영어,수학 정보 입력> ");
		String text = sc.next();	// ex. 홍길동,60,80,50
		
		String[] values = text.split(",");
		System.out.println("이름: " + values[0]);
		System.out.println("국어: " + values[1]);
		System.out.println("영어: " + values[2]);
		System.out.println("수학: " + values[3]);
		
		sc.close();
	}
}
package demo3;

public class StringDemo5 {

	public static void main(String[] args) {
		
		String str = "이것이 자바다";
		System.out.println(str.length());
		
		System.out.println("이것이 자바다".length());
		
		String str2 = "       this is a java           ".trim().toUpperCase().substring(0, 5);
		System.out.println(str2);
	}
}

'자바 > api' 카테고리의 다른 글

demo4  (0) 2019.06.10
demo2  (0) 2019.06.10
demo1  (0) 2019.06.10
package demo2;

public class Contact {
	private int no;
	private String name;
	private String tel;
	private String email;

	public Contact() {}

	public Contact(int no, String name, String tel, String email) {
		super();
		this.no = no;
		this.name = name;
		this.tel = tel;
		this.email = email;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	// 오브젝트의 toString[] 메소드 재정의

	@Override
	public String toString() {
		return "Contact [no=" + no + ", name=" + name + ", tel=" + tel + ", email=" + email + "]";
	}
	
	public Contact copyContact() throws CloneNotSupportedException {
		Object obj = clone();
		Contact c = (Contact)obj;
		return c;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + no;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Contact other = (Contact) obj;
		if (no != other.no)
			return false;
		return true;
	}
}
package demo2;

public class ContactApp {

	public static void main(String[] args) {
		
		Contact c = new Contact(10, "김유신", "010-1111-1111", "kim@naver.com");
		Contact cc = new Contact(10, "김유신", "010-1111-1111", "kim@naver.com");
		
		//int hashcode() : 객체에 부여된 일련번호를 점수로 제공하는 메소드
		int hash = c.hashCode();
		int hash2 = cc.hashCode();
		System.out.println("해쉬코드 값 : " + hash);
		System.out.println("해쉬코드 값 : " + hash2);
		
		// String toString() : 객체의 정보를 문자열로 제공하는 메소드
		//					   설계도의 이름 + "@" + 해시코드값(16진수)
		//					   toString()메소드는 재정의해서 필드에 저장된 값들을 문자열로 이어서 제공하도록
		//					   재정의해서 사용한다.
		String info = c.toString();
		String info2 = cc.toString();
		System.out.println("객체의 정보 : " + info);
		System.out.println("객체의 정보 : " + info2);
		//System.out.println(c);
		//System.out.println(cc);
		//System.out.println(c.toString());
		//System.out.println(cc.toString());	
		
		// boolean equals(Object other) : - 전달받은 다른 객체와 이 객체가 동일한 객체인지 여부를 반환한다.
		boolean res1 = c.equals(cc);
		boolean res2 = cc.equals(c);
		System.out.println(res1);
		System.out.println(res2);
		// 같은 곳을 바라볼 때만(=동일한 객체일 때만) true
	}
}
package demo2;

public class ContactCloneApp {

	public static void main(String[] args) throws Exception {
		
		Contact src = new Contact(100, "홍길동", "010-1111-1111", "hong@gmail.com");
	
		Contact cloneContact = src.copyContact();
		System.out.println(cloneContact.getNo());
		System.out.println(cloneContact.getName());
		System.out.println(cloneContact.getTel());
		System.out.println(cloneContact.getEmail());
	}
}
package demo2;

import java.lang.reflect.Method;

import org.omg.CORBA.Context;

public class ContactReflect {
	public static void main(String[] args) throws Exception {
		Contact c = new Contact(10, "홍길동", "010-1111-2222", "hong@hanmail.com");
				
		Class<?> clazz = c.getClass();
		Method[] methods = clazz.getMethods();
		
		for (Method m : methods) {
			System.out.println(m.getName());
			
		}
	}
}

'자바 > api' 카테고리의 다른 글

demo4  (0) 2019.06.10
demo3  (0) 2019.06.10
demo1  (0) 2019.06.10
package demo1;
/**
 * 덧셈, 뺄셈 기능이 구현된 클래스입니다.
 * @author JHTA
 *
 */
public class Calculator {
	/**
	 * 두 수를 전달받아서 더한 값을 반환합니다.
	 * @param x 숫자
	 * @param y 숫자
	 * @return 덧셈 결과가 반환됨
	 */
	public int plus(int x, int y) {
		int z = x + y;
		return z;
	}
	/**
	 * 두 수를 전달받아서 뺀 값을 반환합니다.
	 * @param x 숫자
	 * @param y 숫자
	 * @return 뺄셈 결과가 반환됨
	 */
	public int minus(int x, int y) {
		int z = x - y;
		return z;
	}
}
package demo1;

public class Hello {

	public static void main(String[] args) {
		System.out.println("안녕, 이클립스");
		
		Calculator cal = new Calculator();
	}
}

'자바 > api' 카테고리의 다른 글

demo4  (0) 2019.06.10
demo3  (0) 2019.06.10
demo2  (0) 2019.06.10
package demo.writer;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

public class PrintWriterDemo1 {

	public static void main(String[] args) throws Exception {
		
		// PrintWriter writer = new PrintWriter("c:/temp/scores.csv");
		
		//File file = new File("c:/temp/scores.csv");
		//PrintWriter writer = new PrintWriter(file);
		
		PrintWriter writer = new PrintWriter(new FileWriter("c:/temp/scores.csv"));
		
		writer.println("김유신,전자공학과,3,3.8");
		writer.println("이순신,기계공학과,3,4.1");
		writer.println("강감찬,무기재료공학과,1,4.5");
		writer.println("홍길동,환경공학과,2,3.2");
		
		writer.flush();
		
		writer.close();
	}
}

'자바 > io' 카테고리의 다른 글

serialization  (0) 2019.06.10
reader  (0) 2019.06.10
file  (0) 2019.06.10
bytestream  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.serialization;

import java.io.Serializable;

public class Employee implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private String name;
	private String position;
	// 직렬화, 역직렬화 대상에서 제외된다.
	private transient int password;
	private Family child;
	
	public Employee() {}

	
	
	public Employee(String name, String position, int password, Family child) {
		super();
		this.name = name;
		this.position = position;
		this.password = password;
		this.child = child;
	}



	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

	public int getPassword() {
		return password;
	}

	public void setPassword(int password) {
		this.password = password;
	}

	public Family getChild() {
		return child;
	}

	public void setChild(Family child) {
		this.child = child;
	}
	
	
}
package demo.serialization;

import java.io.Serializable;

public class Family implements Serializable {

	private String name;
	private int count;
	
	public Family() {}

	public Family(String name, int count) {
		this.name = name;
		this.count = count;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}
}
package demo.serialization;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializationDemo1 {

	public static void main(String[] args) throws Exception {
		
		Family f = new Family("자녀", 2);
		Employee employee = new Employee();
		employee.setName("홍길동");
		employee.setPosition("과장");
		employee.setPassword(1234);
		employee.setChild(f);
		
		FileOutputStream fos = new FileOutputStream("c:/temp/emp.sav");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		
		// void writeObject(Object o)
		// 객체를 직렬화한다.
		oos.writeObject(employee);
		
		oos.close();
	}
}
package demo.serialization;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializationDemo1 {

	public static void main(String[] args) throws Exception {
		
		FileInputStream fis = new FileInputStream("c:/temp/emp.sav");
		ObjectInputStream ois = new ObjectInputStream(fis);
		
		// Object readObject()
		// 스트림으로 읽어들인 데이터를 이용해서 객체를 복원(역직렬화)한다.
		Object obj = ois.readObject();
		// System.out.println(obj);
		Employee emp = (Employee) obj;
		System.out.println("이름 : " + emp.getName());
		System.out.println("직위 : " + emp.getPosition());
		System.out.println("비번 : " + emp.getPassword());
		System.out.println("가족 : " + emp.getChild().getName());
		System.out.println("가족수 : " + emp.getChild().getCount());
		
		ois.close();
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
reader  (0) 2019.06.10
file  (0) 2019.06.10
bytestream  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.reader;

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

public class BufferedReaderDemo1 {

	public static void main(String[] args) throws FileNotFoundException, IOException {
		FileReader reader = new FileReader("c:/temp/data.csv");
		BufferedReader br = new BufferedReader(reader);
		
		/*
		br.readLine();
		br.readLine();
		br.readLine();
		
		// 15~17 이미 읽어서 null 뜸.
		String text1 = br.readLine();
		String text2 = br.readLine();
		String text3 = br.readLine();
		String text4 = br.readLine();
		
		System.out.println(text1);
		System.out.println(text2);
		System.out.println(text3);
		System.out.println(text4);
		*/
		
		String text = null;
		while ((text=br.readLine()) != null) {
			System.out.println(text);
		}
		
		br.close();
	}
}
package demo.reader;

import java.io.BufferedReader;
import java.io.FileReader;

public class BufferedReaderDemo2 {

	public static void main(String[] args) throws Exception {
		BufferedReader reader = new BufferedReader(new FileReader("c:/temp/data.csv"));

		int totalEventCount = 0;
		String text = null;
		while ((text=reader.readLine()) != null) {
			String[] items = text.split(",");
			
			String location = items[5].replace("\"", "");
			if (location.startsWith("서울특별시")) {
			// 발생건수
			int event = Integer.parseInt(items[6]);
			totalEventCount += event;
			}
		}
		System.out.println("서울지역 발생건수 : " + totalEventCount);
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
serialization  (0) 2019.06.10
file  (0) 2019.06.10
bytestream  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.file;

import java.io.File;
import java.util.Date;

public class FileDemo1 {

	public static void main(String[] args) {
		
		// 지정된 파일의 정보를 가지는 파일객체 생성하기
		File file = new File("c:/java_workspace/oop6/Account.java");
		
		// String getName()
		// 파일명 획득하기
		String filename = file.getName();
		System.out.println("파일명 : " + filename);
		
		// long length()
		// 파일 사이즈 획득하기
		long filesize = file.length();
		System.out.println("파일 사이즈 : " + filesize + "바이트");

		// String getPath()
		// 전체 경로 획득하기
		String path = file.getPath();
		System.out.println("전체 경로 : " + path);
		
		// String getParent()
		// 파일이 위치한 디렉토리 경로 획득하기
		String directoryPath = file.getParent();
		System.out.println("디렉토리 경로 : " + directoryPath);
		
		// boolean isFile()
		// 파일인지 여부를 반환한다. 파일인 경우 true를 반환
		boolean isFile = file.isFile();
		System.out.println("파일인가? " + isFile);
		
		// boolean isDirectory()
		// 디렉토리인지 여부를 반환한다. 디렉토리인 경우 true를 반환
		boolean isDirectory = file.isDirectory();
		System.out.println("디렉토리인가 ? " + isDirectory);
		
		// boolean isExist()
		// 존재하는지 여부를 반환한다.
		boolean exist = file.exists();
		System.out.println("존재하는가? " + exist);
		
		// long lastModified()
		// 파일의 최종 수정 일자를 유닉스 시간으로 반환한다.
		long time = file.lastModified();
		System.out.println("최종 수정 일자 : " + time);
		Date date = new Date(time);
		System.out.println("최종 수정 일자 : " + date);
		
	}
}

package demo.file;

import java.io.File;

public class FileDemo2 {

	public static void main(String[] args) throws Exception {
		
		File file = new File("c:/temp/sample.txt");

		// 새 파일 생성하기
		file.createNewFile();
		
	}
}
package demo.file;

import java.io.File;

public class FileDemo3 {

	public static void main(String[] args) {
		
		File dir = new File("c:/temp/source");
		dir.mkdir();
		
		File dirs = new File("c:/temp/resource/images/logo");
		dirs.mkdirs();
	}
}
package demo.file;

import java.io.File;

public class FileDemo4 {

	public static void main(String[] args) {
		
		// 파일의 전체 경로를 활용해서 파일 객체를 초기화
		File file1 = new File("c:/temp/sample.txt");
		
		// 디렉토리명과 파일명을 활용해서 파일객체를 초기화
		File file2 = new File("c:/temp", "sample.txt");

		// 디렉토리 정보를 가진 파일 객체와 파일명을 활용해서 파일 객체를 초기화
		File dir = new File("c:/temp");
		File file3 = new File(dir, "sample.txt");
	}
}
package demo.file;

import java.io.File;

public class FileDemo5 {

	public static void main(String[] args) {
		
		File file1 = new File("c:/temp/source/a.txt");
		file1.delete();
		
		// 폴더 안에 다른 파일이 있으면 폴더는 지워지지 않는다.
		File dir = new File("c:/temp/source");
		dir.delete();
		
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
serialization  (0) 2019.06.10
reader  (0) 2019.06.10
bytestream  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.bytestream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {

	public static void main(String[] args) throws IOException {

		// 지정된 파일을 읽어오는 FileInputStream 생성하기
		FileInputStream in = new FileInputStream("c:/temp/suyoung.jpg");
		
		// 지정된 파일명을 기록하는 FileOutputStream 생성하기
		FileOutputStream out = new FileOutputStream("c:/temp/copy_suyoung.jpg");
		
		int value = 0;
		// InputStream으로부터 1byte씩 읽어온다.
		while ((value = in.read()) != -1) {
			// OutputStream을 사용해서 읽어온 값을 기록한다.
			out.write(value);
		}
		in.close();
		out.close();
	}
}
package demo.bytestream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

public class FileCopy2 {

	public static void main(String[] args) throws Exception {
		InputStream in = new FileInputStream("c:/temp/suyoung.jpg");
		OutputStream out = new FileOutputStream("c:/temp/copycopy_suyoung.jpg");
		
		IOUtils.copy(in, out);
	}
}
package demo.bytestream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class ImageCrawler {

	public static void main(String[] args) throws Exception {
		long startTime = System.currentTimeMillis();
		
		// URL url = new URL("https://img3.daumcdn.net/thumb/R658x0.q70/?fname=https://t1.daumcdn.net/news/201903/26/newsen/20190326101733645qadi.jpg");
		
		// InputStream in = url.openStream();
		// FileOutputStream out = new FileOutputStream("C:/temp/lee.jpg");
		
		FileInputStream in = new FileInputStream("c:/temp/tomcat.exe");
		FileOutputStream out = new FileOutputStream("c:/temp/copy_tomcat.ext");
		
		// 배열에 저장되는 데이터의 개수를 저장하는 변수
		int len = 0;
		// intputStream으로 읽어들인 데이터를 저장하는 배열
		byte[] buf = new byte[1024*8];
		
		// int red(byte[] buf)는 inputStream으로 읽어들인 데이터를
		// 전달받은 배열에 저장하고, 최종적으로 저장된 개수를 반환한다.
		
		while ((len = in.read(buf)) != -1) {
			// void write(byte[] buf, int offset, int len)은 전달받은 배열에 저장된 데이터를
			// offset위치부터 len 개수만큼 기록한다.
			out.write(buf, 0, len);
			
		}
		
		long endTime = System.currentTimeMillis();
		
		//int value = 0;
		//while ((value = in.read()) != -1) {
		//	out.write(value);
		//}
		in.close();
		out.close();
		
	}
}
package demo.bytestream;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;

public class ImageCrawler2 {

	public static void main(String[] args) throws Exception {
		
		URL url = new URL("https://imgnews.pstatic.net/image/346/2019/03/26/0000025295_001_20190326072103336.jpg?type=w647");
		
		InputStream in = url.openStream();
		OutputStream out = new FileOutputStream("c:/temp/미니_소세지.jpeg");
		
		IOUtils.copy(in, out);
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
serialization  (0) 2019.06.10
reader  (0) 2019.06.10
file  (0) 2019.06.10
bridge  (0) 2019.06.10
package demo.bridge;

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

public class BridgeStreamDemo1 {

	public static void main(String[] args) throws Exception {
		
		System.out.println("이름을 입력하세요.");
		
		// 소스(키보드)와 연결된 InputStream
		// InputStream is = System.in;
		// 바이트스트림을 문자스트림으로 변환해주는 InputStreamReader
		// InputStreamReader isr = new InputStreamReader(is);
		// 다른 문자스트림과 연결해서 성능을 향상시키는 BufferedReader
		// BufferedReader br = new BufferedReader(isr);
		
		// 압축
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		
		String text = br.readLine();
		System.out.println(text);
		
		// 키보드와 연결된 스트림 사용하기
		// InputStream in = System.in;
		// 키보드와 연결된 스트림으로 1byte 읽어오기
		// int value = in.read();
		
		// System.out.println(value);
		
	}
}

'자바 > io' 카테고리의 다른 글

writer  (0) 2019.06.10
serialization  (0) 2019.06.10
reader  (0) 2019.06.10
file  (0) 2019.06.10
bytestream  (0) 2019.06.10
package db.utils;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionUtils {

	public static Connection getConnection() throws Exception {
		Class.forName("oracle.jdbc.OracleDriver");
		
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "hr";
		String password = "zxcv1234";
		
		Connection conn = DriverManager.getConnection(url, user, password);
		
		return conn;		
	}
}

'자바 > jdbc' 카테고리의 다른 글

demo3  (0) 2019.06.10
demo2  (0) 2019.06.10
demo1  (0) 2019.06.10

+ Recent posts