티스토리 뷰

학습정리-11-12.txt
0.00MB

 

1. I/O 스트림 이란?

input - 데이터를 읽는 것 (입력하는 것)

output - 데이터를 쓰는 것 (출력하는 것)

 

스트림 : 개울이라는 뜻으로 한쪽 방향으로 흐르는 것을 의미한다. 

그래서 입출력을 I/O 스트림이라고 한다.

(양방향이 아니라 한쪽 방향으로 진행된다. )

 

 

 

 

2. float 에 대하여 설명하시오.

요소의 위치를 설정하기 위한 속성.

div와 같은 블럭 요소들을 가로형 컨텐츠로 표현하기 위해서 사용하는 것이 float 속성이며 block 요소 태그들을 원하는 위치로 끌어 올려주는 역할을 맡고 있다.

float 속성을 주면 평면에서 공중부양한다고 생각하기! (화면에 보이는게 위에서내려다 보는 방향)

▶ float를 사용할 때 주의할 점

우선 한 부모태그 아래에 있는 자식 태그들이 모두 float 속성값을 가질 경우 부모태그는 자식 태그를 인식하지 못한다.(공중에 떠있어서??ㅋㅋ)

이때 집나간 토끼(float 속성값을 가진 자식 태그)를 붙잡기 위해서 부모 태그에 overflow를 사용한다!

overflow: hidden은 넘어가는 내용은 화면에서 보이지 않는다.

overflow: auto는 자식태그들의 크기에 맞춰 부모 태그의 크기가 자동으로 조절 된다.

 

그리고 일부 자식 태그에 float을 주고 나머지 자식 태그에는 float 속성값을 주지 않더라도 뒤에 오는 태그가 float을 적용한 것처럼 따라 오는 문제가 발생하는데 이를 해결하기 위해 해당 태그에 claer: both를 해주어야한다.

 

overflow: hidden 적용 전

See the Pen float by SE (@whaletree) on CodePen.

 

 

overflow: hidden 적용 후

See the Pen float_overflow_hidden by SE (@whaletree) on CodePen.

 

 

 

 

 

3.아래의 포지션 4가지에 대하여 설명하시오.

-static :  기본값, 디폴트 값 (기본적으로 따로 값을 지정해 주지 않은 모든 태그에 생략되어 있는 원래 가지고 있는 속성)

-relative : 자기 자신을 기준으로(값 설정 전에 자기가 있던 위치를 기준으로)

-absolute : 부모태그를 기준으로(relative와 같이 쓰여야 한다)

-fixed : 뷰포트(기기?에서....보여지는 페이지)에서 가장 왼쪽 상단 구석을 기준으로

positon에서 absoute를 쓰려면 부모를 지정해 줘야한다. → 부모로 지정하고 싶은 태그에 relative를 준다!

안그러면 body 태그가 자동으로 부모 태그가 되서 이상한 위치로 간다. (position만 해당됨)

 

z-index : 중첩될 때 어떤 것을 앞으로 할지 결정. 값이 클수록 앞으로 온다. 만약 값이 같을 경우에는 나중에 배치 된 것이 앞으로 온다. 

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <style>
            div{
                width: 100px;
                height: 100px;
                opacity: 0.7;
            }

            div:nth-child(1){
               background-color:  red;
               position: fixed;
           }

           div:nth-child(2){
               background-color:  #00ff00;
               position: absolute;
               top: 50px;
               left: 50px;
           }

           div:nth-child(3){
               background-color:  #0000ff;
               position: absolute;
               top: 100px;
               left: 100px;
           }

           #wrap{
                width: 300px;
                height: 300px;
                position: fixed;
                top: 250px;
                left: 250px;
                background-color: yellow;
                opacity: 1.0;
           }

           #wrap .content{
                width: 100px;
                height: 100px;
                position: absolute;
                top: 100px;
                left: 100px;
                background-color: purple;
           }
        </style>
    </head>
    <body>
        <div></div>
        <div></div>
        <div></div>

        <div id="wrap">
            <div class="content"></div>
        </div>

    </body>
</html>

출력

opacity는 투명도 설정. 1이 기본값으로 낮아질수록 투명해진다.

 

 

 

 

 

3. 아래를 프로그래밍 하시오.

좋은 아침 입니다. 를 love.txt 로 저장 -> 해당 내용을 읽어 들여 love2.txt 로 복사

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

public class IOPractice {

	public static void main(String[] args) {
		
		try {
			OutputStream os = new FileOutputStream("love.txt");
			DataOutputStream dos = new DataOutputStream(os);
			
			dos.writeUTF("좋은 아침 입니다.");
			
			dos.flush();
			
			InputStream is = new FileInputStream("love.txt");
			DataInputStream dis = new DataInputStream(is);
			
			OutputStream os2 = new FileOutputStream("love2.txt");
			dos = new DataOutputStream(os2);
			
			dos.writeUTF(dis.readUTF());
			
			dos.flush();
			dos.close();
			dis.close();
					
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

왜 실행하고나서 메모장 확인하면 앞에 이상한 화살표가 붙는 걸까......

 

아래처럼 하면 정상 출력 된다. 월요일에 질문하기!

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

public class IOPractice {

	public static void main(String[] args) {
		InputStream is = null;
		OutputStream os = null;
		
		try {
			os = new FileOutputStream("love.txt");
			
			String text = "좋은 아침 입니다.";
			
			byte[] stringByte = text.getBytes();
			
			// byte[] stringByte = "좋은 아침입니다.".getBytes();
			
			os.write(stringByte);
			
			os.flush();
			os.close();
			
			is = new FileInputStream("love.txt");
			os = new FileOutputStream("love2.txt");
			
			byte[] readByte = new byte[10];
			
			while(true) {
				int byteCount = is.read(readByte);
				
				if(byteCount == -1)
					break;
				// while 문을 빠져 나가는 거 아닌가?
				// 왜 아래 코드가 정상 실행?
	// 어차피 count가 -1이면 더 이상 읽을 것이 없기 때문에 아래의 코드가 실행될 필요가 없다!
				
			// 읽은 바이트 개수	
			//	System.out.println(byteCount);

				os.write(readByte, 0, byteCount);
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				// null이 아닐 때인 이유는 초기값이 null이고 실행되면 null이 아니게 되기 때문에 
				// 실행이 되었다면 닫아서 끝내주라는 의미이다.
				if(is != null)
					is.close();
				
				if(os != null) {
					os.flush();
					os.close();
				}
					
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

	}
}

 

객체로.......

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

class IOCopy{
	public static final String FILE_NAME = "love.txt";
	
	public boolean saveWords(String words) {
		boolean isDone = true; // boolean 변수명 앞에 is를 붙이는 관행이??
		
		OutputStream os = null;
		try {
			os = new FileOutputStream(FILE_NAME);
			byte[] buffer = words.getBytes();
			
			os.write(buffer);			
			
		} catch (Exception e) {
			e.printStackTrace();
			isDone = false;
		}finally {
			try {
				if(os != null)
					os.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return isDone;
	}
	
	public boolean copyFile(String source, String destination) {
		boolean isDone = true;
		
		OutputStream os = null;
		InputStream is = null;
		try {
			is = new FileInputStream(source);
			os = new FileOutputStream(destination);
			
			byte[] buffer = is.readAllBytes();
			// 한방에 모든 byte를 다 읽는 함수!! 반복문 안써도 된다...
			// 추가 설명은 더보기란 참고
			
			os.write(buffer);
					
		} catch (Exception e) {
			isDone = false;
			e.printStackTrace();
		}finally {
			try {
				if(os != null)
					os.flush(); os.close();
				
				if(is != null)
					is.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		return isDone;
	}
	
}

public class IOPractice {

	public static void main(String[] args) {
		IOCopy ioCopy = new IOCopy();
		
		ioCopy.saveWords("좋은 아침입니다.");
		ioCopy.copyFile("love.txt", "love2.txt");
		// 원본 파일 이름, 카피 한 내용을 저장할 파일 이름
	}
}

 

추가 함수 설명 참고

 

 

 

 

4.금일 배운 내용을 바탕으로, 아래를 프로그래밍 하시오.

나라 이름과 인구를 입력하세요.(예: Korea 5000)

나라 이름, 인구 >> Korea 5000

나라 이름, 인구 >> USA 1000000

나라 이름, 인구 >> Swiss 2000

나라 이름, 인구 >> France 3000

나라 이름, 인구 >> 그만

 

인구 검색 >> France

France의 인구는 3000

인구 검색 >> 스위스

스위스 나라는 없습니다.

인구 검색 >> 그만

 

그만"이 입력될 때까지 나라 이름과 인구를 입력 받아 저장하고,

다시 나라 이름을 입력받아 인구를 출력하는 프로그램을 해시맵을 이용하여 아래와 같이 작성 하였다.

 

위의 CountryMap 에서 아래의 함수를 추가하여 테스트 하시오

 

// country.bin 에 HashMap<String, Integer> map; 안에 저장된 나라와 인구수를 저장

// I/O Stream 사용

public boolean saveFileMap() {

 

}

// I/O Stream 사용

// 저장된 country.bin 을 읽어 들여, HashMap<String, Integer> 으로 반환

public HashMap<String, Integer> readFileMap() {

 

}

// I/O Stream 사용

// 저장된 country.bin 을 읽어 들여, 저장된 나라와 인구수를 출력

public void printFileMap() {

 

}

 

import java.util.HashMap;

import java.util.Scanner;

 

import javax.lang.model.util.ElementScanner6;

 

class CountryMap {

private HashMap<String, Integer> map;

 

public CountryMap() {

map = new HashMap<>();

}

 

public HashMap<String, Integer> getMap() {

 

try {

System.out.println("나라 이름과 인구를 입력하세요.(예: Korea 5000)");

Scanner sc = new Scanner(System.in);

 

int population = 0;

String country = " ";

 

while (true) {

System.out.print("나라 이름, 인구 >> ");

country = sc.next();

 

if (country.equals("그만")) // 입력 "그만" 하면 입력 종료

break;

 

population = sc.nextInt();

map.put(country, population);

}

 

 

} catch (Exception e) {

System.out.println("잘못된 입력입니다. 다시 입력하세요.");

getMap();

}

 

return map;

}

 

public void setMap(HashMap<String, Integer> map) {

this.map = map;

}

 

public void search() {

 

try {

// 키 입력받아서 검색해서 정보 출력하기 그만할때까지

// 없으면 없습니다 출력

Scanner sc = new Scanner(System.in);

 

String key = " ";

while (true) {

System.out.print("인구 검색 >> ");

key = sc.next();

 

if (key.equals("그만")) // 입력 "그만" 하면 검색 종료

break;

else if (!map.containsKey(key)) { // map의 key에 key가 있지 않으면

System.out.println(key + " 나라는 없습니다.");

continue;

}

System.out.println(key + " " + map.get(key)); // 키값으로 내용 출력

}

 

} catch (Exception e) {

System.out.println("잘못된 입력입니다. 다시 입력하세요.");

getMap();

}

 

}

}

 

public class ContryMapTest {

public static void main(String[] args) {

CountryMap countryMap = new CountryMap();

countryMap.getMap();

 

System.out.println();

countryMap.search();

 

}

}

와!!!! 되는데......이게 왜 되는지 정확하게 모르겠네........ㅋㅋㅋ 엉망진창으로 굴러가네.........뭔가 코드가 이상한거 같은데.....savefileMap은 왜 boolean일까.....ㅎ...수정 필수ㅠㅠㅠ
심각하다...점점 갈수록 수업 정리 문제 안풀리는데.....풀고도 왜 그런지 모르고....ㅠ 입출력 어렵다....이대로 괜찮은 건가...
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

class CountryMap {
	private HashMap<String, Integer> map;

	public CountryMap() {
		map = new HashMap<>();
	}

	public HashMap<String, Integer> getMap() {

		try {
			System.out.println("나라 이름과 인구를 입력하세요.(예: Korea 5000)");
			Scanner sc = new Scanner(System.in);

			int population = 0;
			String country = " ";

			while (true) {
				System.out.print("나라 이름, 인구 >> ");
				country = sc.next();

				if (country.equals("그만")) // 입력 "그만" 하면 입력 종료
					break;

				population = sc.nextInt();
				map.put(country, population);
			}

		} catch (Exception e) {
			System.out.println("잘못된 입력입니다. 다시 입력하세요.");
			getMap();
		}

		return map;
	}

	public void setMap(HashMap<String, Integer> map) {
		this.map = map;
	}

	public void search() {

		try {
			// 키 입력받아서 검색해서 정보 출력하기 그만할때까지
			// 없으면 없습니다 출력
			Scanner sc = new Scanner(System.in);

			String key = " ";
			while (true) {
				System.out.print("인구 검색 >> ");
				key = sc.next();

				if (key.equals("그만")) // 입력 "그만" 하면 검색 종료
					break;
				else if (!map.containsKey(key)) { // map의 key에 key가 있지 않으면
					System.out.println(key + " 나라는 없습니다.");
					continue;
				}
				System.out.println(key + " " + map.get(key)); // 키값으로 내용 출력
			}

		} catch (Exception e) {
			System.out.println("잘못된 입력입니다. 다시 입력하세요.");
			getMap();
		}

	}

	// country.bin 에 HashMap<String, Integer> map; 안에 저장된 나라와 인구수를 저장
	// I/O Stream 사용
	public boolean saveFileMap() {
		
		boolean boo = false;
		
		OutputStream os = null;
		DataOutputStream dos = null;

		try {
			os = new FileOutputStream("country.bin");
			dos = new DataOutputStream(os);

			Set<String> set = map.keySet();

			for (String str : set) {
				dos.writeUTF(str);
				dos.writeInt(map.get(str));
				
			}

			boo = true;

		} catch (Exception e) {
			e.printStackTrace();
			boo = false;
		} finally {
			try {
				if (os != null)
					os.close();
				if(dos != null)
					dos.close();
			} catch (Exception e2) {

			}

		}

		return boo;

	}
    // 반환 값이 boolean인 이유는 정상 실행되는 것을 확인해주기 위해서!
    // 정상 실행 되면 true, 오류 발생하면 false 반환
    

	// I/O Stream 사용
	// 저장된 country.bin 을 읽어 들여, HashMap<String, Integer> 으로 반환
	public HashMap<String, Integer> readFileMap() {
		try {
        // 새로운 객체를 생성하지 않고 가장 위에 있는 map을 불러서 사용하게 되면
        // 이미 저장되어 있는 값을 사용하기 때문에 정상 출력
        // 해당 함수는 값이 들어가지 않는다....무조건 새로 객체 생성해서 while문 돌려야되는데...
        // 내가 짠 코드는 아예 실행이 되지 않고, 이미 저장된 값이 사용된 것이다.
			InputStream is = new FileInputStream("country.bin");
			DataInputStream dis = new DataInputStream(is);

			
			String country = dis.readUTF();
			int population = dis.readInt();

			map.put(country, population);
			
			dis.close();
			is.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;

	}

	// I/O Stream 사용
	// 저장된 country.bin 을 읽어 들여, 저장된 나라와 인구수를 출력
	public void printFileMap() {
		try {
			map = readFileMap();

			Set<String> set = map.keySet();

			for (String str : set) {
				System.out.println("나라: " + str + " / 인구 수: " + map.get(str));
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}

public class ContryMapTest {
	public static void main(String[] args) {
		CountryMap countryMap = new CountryMap();
		countryMap.getMap();

		System.out.println();
		countryMap.search();

		System.out.println();

		boolean boo = countryMap.saveFileMap();
		System.out.println(boo);

		countryMap.printFileMap();

	}
}

 

선생님 코드

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

class CountryMap {
	private HashMap<String, Integer> map;

	public CountryMap() {
		map = new HashMap<>();
	}

	public HashMap<String, Integer> getMap() {

		try {
			System.out.println("나라 이름과 인구를 입력하세요.(예: Korea 5000)");
			Scanner sc = new Scanner(System.in);

			int population = 0;
			String country = " ";

			while (true) {
				System.out.print("나라 이름, 인구 >> ");
				country = sc.next();

				if (country.equals("그만")) // 입력 "그만" 하면 입력 종료
					break;

				population = sc.nextInt();
				map.put(country, population);
			}

		} catch (Exception e) {
			System.out.println("잘못된 입력입니다. 다시 입력하세요.");
			getMap();
		}

		return map;
	}

	public void setMap(HashMap<String, Integer> map) {
		this.map = map;
	}

	public void search() {

		try {
			// 키 입력받아서 검색해서 정보 출력하기 그만할때까지
			// 없으면 없습니다 출력
			Scanner sc = new Scanner(System.in);

			String key = " ";
			while (true) {
				System.out.print("인구 검색 >> ");
				key = sc.next();

				if (key.equals("그만")) // 입력 "그만" 하면 검색 종료
					break;
				else if (!map.containsKey(key)) { // map의 key에 key가 있지 않으면
					System.out.println(key + " 나라는 없습니다.");
					continue;
				}
				System.out.println(key + " " + map.get(key)); // 키값으로 내용 출력
			}

		} catch (Exception e) {
			System.out.println("잘못된 입력입니다. 다시 입력하세요.");
			getMap();
		}

	}

	// country.bin 에 HashMap<String, Integer> map; 안에 저장된 나라와 인구수를 저장
	// I/O Stream 사용
	
	private static final String FILE_NAME = "country.bin";
	public boolean saveFileMap() {
		
		boolean isDone = true;
		
		OutputStream os = null;
		DataOutputStream dos = null;

		try {
			os = new FileOutputStream(FILE_NAME);
			dos = new DataOutputStream(os);

			Set<String> set = map.keySet();

			for (String key : set) {
				String country = key;
				Integer population = map.get(key);
				
				dos.writeUTF(country);
				dos.writeInt(population);
				
			}
			
			isDone = true;

		} catch (Exception e) {
			e.printStackTrace();
			isDone = false;
		} finally {
			try {
				if (os != null)
					os.close();
				if(dos != null)
					dos.close();
			} catch (Exception e2) {

			}

		}

		return isDone;

	}


	// I/O Stream 사용
	// 저장된 country.bin 을 읽어 들여, HashMap<String, Integer> 으로 반환
	public HashMap<String, Integer> readFileMap() {
		HashMap<String, Integer> countryMap = new HashMap<>();
		
		InputStream is = null;
		DataInputStream dis = null;
		try {
			is = new FileInputStream(FILE_NAME);
			dis = new DataInputStream(is);
			
			// available()은 dis를 끝까지 읽었느냐를 확인하는 함수??
			while(dis.available() > 0) {
				String country = dis.readUTF();
				int population = dis.readInt();
				
				countryMap.put(country, population);
				System.out.println(countryMap);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (is != null)
					is.close();
				if(dis != null)
					dis.close();
			} catch (Exception e2) {

			}
		}
		return countryMap;

	}

	// I/O Stream 사용
	// 저장된 country.bin 을 읽어 들여, 저장된 나라와 인구수를 출력
	public void printFileMap() {
		Set<String> set = map.keySet();

		for (String key : set) {
			String country = key;
			Integer population = map.get(key);

			System.out.println("나라" + country + "  인구" + population);
		}
	}

}

public class ContryMapIOTest {
	public static void main(String[] args) {
		/*
		CountryMap countryMap = new CountryMap();
		countryMap.getMap();

		System.out.println();
		countryMap.search();

		System.out.println();
		*/
		
		CountryMap map = new CountryMap();
		map.getMap();
		map.saveFileMap();
		
		System.out.println();
		
		map.readFileMap();
		map.printFileMap();

	}
}

available()?

 


진척도 57번

See the Pen position & z-index by SE (@whaletree) on CodePen.

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함