[IO-2] Writer(CSVWriter, XMLWriter, JSONWriter)

seratpfk·2022년 8월 11일
0

JAVA

목록 보기
89/96

txt 파일에 데이터 생성

  • m1.txt
	public static void m1() {
		File dir = new File("C:\\storage");
		if(dir.exists() == false) {
			dir.mkdirs();
		}
		File file = new File(dir, "m1.txt");
		FileWriter fw = null;
		try {
			// C:\\storage\\m1.txt 파일과 연결되는 문자 출력 스트림 생성
			// 출력 스트림이 생성되면 파일도 새로 생성됨
			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();
			}
		}
	}
  • m2.txt
		public static void m2() {
		File file = new File("C:\\storage", "m2.txt");
		FileWriter fw = null;
		try {
			// 출력 스트림 생성(파일도 함께 생성)
			fw = new FileWriter(file);
			// 출력할 데이터
			// 1. 1글자 : int
			// 2. 여러 글자 : char[], String
			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문을 의미함
  4. 형식
    try(스트림 생성) {
    코드
    } catch(Exception e) {
    e.printStackTrace();
    }
  • m3.txt
	public static void m3() {
		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();
		}
	}
  • m4.txt
		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();
		}
	}
  • m5.txt
	public static void m5() {
		// 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();
			}
		}
	}
  • m6.txt
	public static void m6() {
		// PrintWriter 클래스는 write() 메소드 외
		// 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 (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(out != null) out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

CSVWriter

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

CSVWriter 값 출력

C:\storage\product.csv
제품번호,제품명,가격\n
100,새우깡,1500\n
101,양파링,2000\n
102,홈런볼,3000\n

	public static void main(String[] args) {
		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();
			}
		}
	}
}

XML

  1. eXtensible Markup Language
  2. 확장 마크업 언어
  3. 표준 마크업 언어인 HTML의 확장 버전
  4. 정해진 태그(<>) 외 사용자 정의 태그 사용
public class XMLWriter {
	public static void main(String[] args) {
		try {
			// Document 생성(문서 생성)
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.newDocument();
			document.setXmlStandalone(true);  // standalone="no" 제거
			// 추가 2라인
			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");
			transformer.setOutputProperty("doctype-public", "yes");  // document.setXmlStandalone(true); 하면 개행이 안 되기 때문에 추가
			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

  1. JavaScript Object Notation
  2. 자바스크립트 객체 표기법
  3. 객체 : { }
  4. 배열 : [ ]
    *JSON-Java(JSON in Java) 라이브러리
  5. 객체 : JSONObject 클래스(Map 기반)
  6. 배열 : JSONArray 클래스(List 기반)
	public static void m2() {
		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}]

	public static void m4() {
		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);
		}
		// 향상 for문 : get() 메소드로 동작. get() 메소드는 Object를 반환.
		for(Object o : arr) {
			JSONObject obj = (JSONObject)o;
			String name = obj.getString("name");
			int age = obj.getInt("age");
			System.out.println(name + "," + age);
		}
	}

출력:
제임스,30
에밀리,40
제임스,30
에밀리,40

  • list를 json String으로 만들어서 c:\storage\product.json 파일에 write()
		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);
		JSONArray arr = new JSONArray();
		for(List<String> line : list) {
			JSONObject obj = new JSONObject();
			obj.put("number", line.get(0));
			obj.put("name", line.get(1));
			obj.put("price", line.get(2));
			arr.put(obj);
		}
		File file = new File("c:\\storage", "product.json");
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(file);
			bw = new BufferedWriter(fw);
			bw.write(arr.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(bw != null) {
					bw.close();
				}
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
	}
}

0개의 댓글