버글버글

Java 수업 기록 (22) IO - Writer 본문

java/java 수업 기록

Java 수업 기록 (22) IO - Writer

Bugle 2022. 8. 14. 00:00
반응형

▶ IO 

▶ writer 

1. 파일과 연결되는 문자 출력 스트림 생성

2. 출력 스트림이 생성되면 파일도 새로 생성됨

3. 출력할 데이터
    1) 1글자 : int
    2) 여러 글자 : char[], String

 

생성예시)

		File dir = new File("C:\\storage");
		if(dir.exists() == false) {
			dir.mkdirs();
		}
		
		File file = new File(dir, "m1.txt");
		
		FileWriter fw = null;
		try {
			fw = new FileWriter(file);  // new FileWriter("C:\\storage\\m1.txt")와 같음
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fw != null) {
					fw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

 

1 글자 쓰기 예시)

		File file = new File("C:\\storage", "m2.txt");
		
		FileWriter fw = null;
		try {

			fw = new FileWriter(file);
			
			int c = 'I';
			char[] cbuf = {' ', 'a', 'm'};
			String str = " IronMan";
			
			fw.write(c);
			fw.write(cbuf);
			fw.write(str);
			
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fw != null) {
					fw.close();
				}
			} catch(IOException e) {
				e.printStackTrace();
			}
		}

 

▶ try - catch - resources문

1. resources는 자원을 의미함
2. 여기서 자원은 스트림(stream)을 의미함
3. 스트림의 종료(close)를 자동으로 처리하는 try-catch문을 의미함

* 형식

		    try(스트림 생성) {
		        코드
		    } catch(Exception e) {
		        e.printStackTrace();
		    }

예시)

		File file = new File("C:\\storage", "m3.txt");
		try (FileWriter fw = new FileWriter(file)) {
			
			fw.write("나는 아이언맨이다.");
			fw.write("\n");
			fw.write("너는 타노스냐?\n");
			
		} catch(IOException e) {
			e.printStackTrace();
		}		
	}

▶ char와 string의 글자 쓰기

예시)

		File file = new File("C:\\storage", "m4.txt");
		
		try(FileWriter fw = new FileWriter(file)) {
			
			char[] cbuf = {'a', 'b', 'c', 'd', 'e'};
			String str = "abcde";
			
			fw.write(cbuf, 0, 2);  // 인덱스 0부터 2글자만 씀
			fw.write(str, 2, 3);   // 인덱스 2부터 3글자만 씀
			
		} catch (IOException e) {
			e.printStackTrace();
		}

bufferedWriter

FileWriter는 느리기 때문에 빠른 속도가 필요한 경우 BufferedWriter를 추가해서 함께 사용한다.

 - 보조스트림이라고도 하며, 메인스트림이 없으면 사용이 불가하다.

예시)

		File file = new File("C:\\storage", "m5.txt");
		
		FileWriter fw = null;
		BufferedWriter bw = null;
		
		try {
			
			fw = new FileWriter(file);
			bw = new BufferedWriter(fw);
			
			bw.write("오늘은 수요일인데 수업이 안 끝나요. ㅎㅎㅎ");
			
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 메인 스트림은 닫을 필요가 없음(자동으로 메인 스트림이 닫히므로)
				if(bw != null) {
					bw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

 

 PrintWriter

- writer() 메소드 이외에 print(), println() 메소드를 지원한다.

예시)

		File file = new File("c:\\storage", "m6.txt");
		
		PrintWriter out = null;
		
		try {
			
			out = new PrintWriter(file);
			
			// write() 메소드는 줄 바꿈을 "\n" 으로 처리한다.
			out.write("안녕하세요\n");
			
			// println() 메소드는 자동으로 줄 바꿈이 삽입된다.
			out.println("반갑습니다.");
			out.println("처음뵙겠습니다.");
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(out != null) out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

▶ CSV writer 

1. Comma Separate Values
2. 콤마로 분리된 값들
3. 확장자 .csv인 파일(기본 연결프로그램-엑셀, 메모장으로 오픈 가능)

* 다량의 데이터를 만들때 사용하고 그 외에는 JSON, XML이 많이 쓰인다.

예시)

C:\storage\product.csv
제품번호,제품명,가격\n
100,새우깡,1500\n
101,양파링,2000\n
102,홈런볼,3000\n
		List<String> header = Arrays.asList("제품번호", "제품명", "가격");
		List<String> product1 = Arrays.asList("100", "새우깡", "1500");
		List<String> product2 = Arrays.asList("101", "양파링", "2000");
		List<String> product3 = Arrays.asList("102", "홈런볼", "3000");
		
		List<List<String>> list = Arrays.asList(header, product1, product2, product3);
		
		File file = new File("C:\\storage", "product.csv");
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(file, StandardCharsets.UTF_8);
			bw = new BufferedWriter(fw);
			for(int i = 0, length = list.size(); i < length; i++) {
				List<String> line = list.get(i);
				for(int j = 0, size = line.size(); j < size; j++) {
					if(j == size - 1) {
						bw.write(line.get(j) + "\n");
					} else {
						bw.write(line.get(j) + ",");
					}
				}
			}
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(bw != null) {
					bw.close();
				}
			} catch(IOException e) {
				e.printStackTrace();
			}
		}

▶ XMLwriter 

1. eXtensible Markup Language
2. 확장 마크업 언어
3. 표준 마크업 언어인 HTML의 확장 버전
4. 정해진 태그(<>) 외 사용자 정의 태그 사용

예시)

  <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <products>
            <product>
                    <number>100</number>
                    <name>새우깡</name>
                    <price>1500</price>
            </product>
            <product>
                    <number>101</number>
                    <name>양파링</name>
                    <price>2000</price>
            </product>
            <product>
                    <number>102</number>
                    <name>홈런볼</name>
                    <price>3000</price>
            </product>
<products>
		try {
			
			// Document 생성(문서 생성)
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.newDocument();
			document.setXmlStandalone(true);
			
			// Document에 products 추가
			Element products = document.createElement("products");
			document.appendChild(products);
						
			List<String> product1 = Arrays.asList("100", "새우깡", "1500");
			List<String> product2 = Arrays.asList("101", "양파링", "2000");
			List<String> product3 = Arrays.asList("102", "홈런볼", "3000");
			
			List<List<String>> list = Arrays.asList(product1, product2, product3);
			
			for(List<String> line : list) {
				// 태그 생성
				Element product = document.createElement("product");
				Element number = document.createElement("number");
				number.setTextContent(line.get(0));
				Element name = document.createElement("name");
				name.setTextContent(line.get(1));
				Element price = document.createElement("price");
				price.setTextContent(line.get(2));
				// 태그 배치
				products.appendChild(product);
				product.appendChild(number);
				product.appendChild(name);
				product.appendChild(price);
			}
			
			// XML 생성
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty("encoding", "UTF-8");
			transformer.setOutputProperty("indent", "yes");	// indent = 들여쓰기
			transformer.setOutputProperty("doctype-public", "yes");
			
			Source source = new DOMSource(document);
			File file = new File("C:\\storage", "product.xml");
			StreamResult result = new StreamResult(file);
			
			transformer.transform(source, result);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

 

▶ JSON writer 

* JSON GitHub 

https://github.com/stleary/JSON-java/blob/master/README.md

 

GitHub - stleary/JSON-java: A reference implementation of a JSON package in Java.

A reference implementation of a JSON package in Java. - GitHub - stleary/JSON-java: A reference implementation of a JSON package in Java.

github.com

1. JavaScript Object Notation
2. 자바스크립트 객체 표기법
3. 객체 : { }
4. 배열 : [ ]

JSON-Java(JSON in Java) 라이브러리
1. 객체 : JSONObject 클래스(Map 기반)
2. 배열 : JSONArray 클래스(List 기반)

예시)

            JSONObject obj = new JSONObject();
            obj.put("name", "홍길동");
            obj.put("age", 30);
            obj.put("man", true);
            obj.put("height", 160.5);
            System.out.println(obj.toString());
            // {"name":"홍길동","man":true,"age":30,"height":160.5}
            JSONObject obj1 = new JSONObject();
            obj1.put("name", "제임스");
            obj1.put("age", 30);

            JSONObject obj2 = new JSONObject();
            obj2.put("name", "에밀리");
            obj2.put("age", 40);

            JSONArray arr = new JSONArray();
            arr.put(obj1);
            arr.put(obj2);

            System.out.println(arr.toString());
            // [{"name":"제임스","age":30},{"name":"에밀리","age":40}]
            String str = "{\"name\":\"홍길동\",\"man\":true,\"age\":30,\"height\":160.5}";

            JSONObject obj = new JSONObject(str);

            String name = obj.getString("name");
            boolean man = obj.getBoolean("man");
            int age = obj.getInt("age");
            double height = obj.getDouble("height");

            System.out.println(name);
            System.out.println(man);
            System.out.println(age);
            System.out.println(height);
            // 홍길동
  	    // true
	    // 30
	    // 160.5

* JSON Array

		String str = "[{\"name\":\"제임스\",\"age\":30},{\"name\":\"에밀리\",\"age\":40}]";
		
		JSONArray arr = new JSONArray(str);
		
		// 일반 for문
		for(int i = 0, length = arr.length(); i < length; i++) {
			JSONObject obj = arr.getJSONObject(i);
			String name = obj.getString("name");
			int age = obj.getInt("age");
			System.out.println(name + "," + age);
		}
		// 제임스,30
		// 에밀리,40
        
        	// 향상 for문
        	for(Object o : arr) {
			JSONObject obj = (JSONObject)o;		// 캐스팅
			String name = obj.getString("name");
			int age = obj.getInt("age");
			System.out.println(name + "," + age);

= 향상 for문은, 기본적으로 get() 메소드로 동작한다. get() 메소드는 Object를 반환 한다.

   그래서 JSONObject 대신 object를 넣고, 후에 JSONOBject를 선언하고 캐스팅을 진행한다.

반응형