package Day11;
import java.io.FileReader;
public class ExceptionTest1 {
static void main() {
FileReader file;
try {
// 파일을 읽어오는 클래스 FileReader 객체 생성 a.txt 파일
file = new FileReader("a.txt");
int i;
// file.read() 파일 한글자씩 읽어 i = 문자로 읽어와서 글자 더 이상 없으면 -1
while ((i = file.read()) != -1) {
System.out.print((char) i);
}
// 파일 닫아주기
file.close();
} catch (Exception e) {
System.out.println("예외처리 루틴: " + e + "파일이 존재하지 않는다.");
}
}
}
package Day11;
import java.io.FileReader;
public class ExceptionTest2 {
static void main(String[] args) throws Exception {
FileReader file = new FileReader("a.txt");
int i;
while ((i = file.read()) != -1) {
System.out.print((char) i);
}
file.close();
}
}
package Day11;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionTest3 {
static void main() {
Scanner sc = new Scanner(System.in);
int num = 0;
int flag = 0;
while (flag == 0) {
flag= 1;
try {
System.out.print("숫자 입력 = ");
num = sc.nextInt();
System.out.println("입력 받은 숫자는 = " + num);
} catch (InputMismatchException e) {
flag = 0;
sc.nextLine();
System.out.println("정상적인 숫자를 입력하세요.");
}
}
}
}
package Day11;
class Car {
private String modelName;
public Car(String modelName) {
this.modelName = modelName;
}
// 내부 클래스는 private 접근 가능 나만의 클래스이기 때문
class Engine {
void start() {
System.out.println(modelName + "의 엔진이 켜졌습니다.");
}
}
public void startCar() {
Car.Engine e = new Engine();
e.start();
}
}
public class InnerClassTset {
static void main() {
Car mycar = new Car("포르쉐");
mycar.startCar();
}
}
package Day11;
interface XOR {
void abc();
}
public class LanbdaTest {
static void main() {
// 인터페이스도 객체화는 가능 (오버라이딩 했을 때)
XOR xor = new XOR() {
@Override
public void abc() {
System.out.println("abc");
}
};
// 람다식
XOR xor1 = () -> System.out.println("kor");
xor1.abc();
}
}
package PDFTest;
// PDF 만들기
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.Year;
import java.util.HashMap;
public class PDFTest1 {
public static void main(String[] args) throws IOException {
// 맵 객체
HashMap<String , String> bookInfo = new HashMap<>();
// 맵에 데이터 추가
bookInfo.put("title" , "한글자바");
bookInfo.put("author" , "홍길동");
bookInfo.put("publisher" , "한글 출판사");
bookInfo.put("year" , String.valueOf(Year.now().getValue()));
bookInfo.put("price", "25000");
bookInfo.put("pages", "400");
//Pdf 쓰는 객체 생성 -> 생성자 매개변수 FileOutputStream () book.pdf
PdfWriter writer = new PdfWriter(new FileOutputStream("book.pdf"));
// Pdf 문서 객체 생성 -> 생성자 매개변수 PdfWriter
PdfDocument pdf = new PdfDocument(writer);
//Document (진짜문서) 객체 생성 -> 생성자 매개변수 PdfDocument
Document document = new Document(pdf);
//PDF 폰트 객체 생성 성상 세팅 글꼴 인 코딩
PdfFont font = PdfFontFactory.createFont("NanumBuJangNimNunCiCe.ttf", PdfEncodings.IDENTITY_H);
// 세팅된 PDF 폰트 객체를 문서에 Set
document.setFont(font);
// 향상된 for 문
// 문자열 Key : 맵 키 꾸러미 Set
for (String key : bookInfo.keySet()) {
// 실제 PDF 쓰는데
// paragraph 객체를 생성하면 써질 글자를 생성자 매개변수 넣어준다
// title: 한글 자바
Paragraph paragraph = new Paragraph(key + ":" + bookInfo.get(key));
// 문서에 쓰기
document.add(paragraph);
}
//문서를 닫아준다
document.close();
// 끝났기 때문에 파일 생성 출력
System.out.println("pdf 파일이 생성되었습니다");
}
}
package PDFTest;
// PDF 만들기 (표)
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.UnitValue;
// 입력 -> List -> PdfWriter -> PdfDocument -> Documnet
// 테이블 생성 및 세팅 -> HeadCell 생성 및 테이블에 추가
// List에 있는 전체 데이터 반복문 돌면서 Cell에 추가하고 후에 테이블 추가 작업을 한다.
// List 내용 전체가 끝날 때까지
// 이게 끝나면 table 완성 -> document에 추가한다.
// document를 close하면 끝
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.*;
public class PDFTest2 {
public static void main(String[] args) throws IOException {
// 문자열 -> 생성될 PDF 이름
String dest = "book_table.pdf";
// createPdf static -> 객체 생성하고 불러야 한다.
new PDFTest2().createPdf(dest);
}
public void createPdf(String dest) throws IOException {
List<Map<String, String>> books = createDummyData();
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, PageSize.A4);
PdfFont headerFont =
PdfFontFactory.createFont("NanumBuJangNimNunCiCe.ttf", "Identity-H");
PdfFont bodyFont =
PdfFontFactory.createFont("NanumBuJangNimNunCiCe.ttf", "Identity-H");
float[] columnWidths = {1, 2, 2, 2, 2, 2};
Table table = new Table(UnitValue.createPointArray(columnWidths));
table.setWidth(UnitValue.createPercentValue(100));
table.addHeaderCell(new Cell().add(new Paragraph("순번")).setFont(headerFont));
table.addHeaderCell(new Cell().add(new Paragraph("제목")).setFont(headerFont));
table.addHeaderCell(new Cell().add(new Paragraph("저자")).setFont(headerFont));
table.addHeaderCell(new Cell().add(new Paragraph("출판사")).setFont(headerFont));
table.addHeaderCell(new Cell().add(new Paragraph("출판일")).setFont(headerFont));
table.addHeaderCell(new Cell().add(new Paragraph("이미지")).setFont(headerFont));
int rowNum = 1;
for (Map<String, String> book : books) {
String title = book.get("title");
String authors = book.get("authors");
String publisher = book.get("publisher");
String publishedDate = book.get("publishedDate"); // 수정
String thumbnail = book.get("thumbnail");
table.addCell(new Cell().add(new Paragraph(String.valueOf(rowNum))).setFont(bodyFont));
table.addCell(new Cell().add(new Paragraph(title)).setFont(bodyFont));
table.addCell(new Cell().add(new Paragraph(authors)).setFont(bodyFont));
table.addCell(new Cell().add(new Paragraph(publisher)).setFont(bodyFont));
table.addCell(new Cell().add(new Paragraph(publishedDate)).setFont(bodyFont));
ImageData imageData = ImageDataFactory.create(new File(thumbnail).toURI().toURL());
Image img = new Image(imageData);
img.setAutoScale(true);
table.addCell(new Cell().add(img));
rowNum++;
}
document.add(table);
document.close();
System.out.println("PDF 생성 완료!");
}
private static List<Map<String, String>> createDummyData() {
List<Map<String, String>> books = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.print("책 개수를 입력하세요: ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // 개행 문자 제거
for (int i = 1; i <= bookCount; i++) {
Map<String, String> book = new HashMap<>();
System.out.printf("%n[%d번째 책 정보 입력]%n", i);
System.out.print("제목: ");
book.put("title", scanner.nextLine());
System.out.print("저자: ");
book.put("authors", scanner.nextLine());
System.out.print("출판사: ");
book.put("publisher", scanner.nextLine());
System.out.print("출판일(YYYY-MM-DD): ");
book.put("publishedDate", scanner.nextLine());
System.out.print("썸네일 경로: ");
book.put("thumbnail", scanner.nextLine());
books.add(book);
}
scanner.close();
return books;
}
}
package APITest;
// kakaoAPI 활용해 도서 검색 프로그램 만들기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class BookAPITest {
public static StringBuilder apiCall(String input) throws IOException {
// URLEncoder -> 웹에서 사용하는 방식으로 문자열을 변환시킨다
String query = URLEncoder.encode(input);
// 카카오에서 너 책 검색하려면 이 URL을 사용해서 접근해
String apiUrl = "https://dapi.kakao.com/v3/search/book?query=" + query;
// 위에 URL 문자열 완성 -> URL 객체를 완성
URL url = new URL(apiUrl);
// 웹 -> 아까 만든 URL 객체를 가지고 openConnection
// 카카오서버랑 나랑 연결된 객체 HttpURLConnection
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 방식 GET
con.setRequestMethod("GET");
// 카카오 서버 인증 -> Authorization "KakaoAK 카카오 REST API 키"
con.setRequestProperty("Authorization", "KakaoAK " + "bd5567fffa07c60e6dfc0b546270449f");
// BufferedReader: 카카오 서버가 데이터를 보내면 받을 객체
// 받는 데이터 BufferedReader
// 카카오 서버 <-> 연결 카카오가 보낸 걸 받는다
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
// 문자열 변수 생성
String inputLine;
// StringBuilder 문자열이랑 똑같은 List 같이 쓸 때
StringBuilder content = new StringBuilder();
// 문자열 inputLine <----- BufferReader -> readLine 한 줄씩
while ((inputLine = in.readLine()) != null) { // 데이터 없을 때까지
// StringBuilder에 inputLine 데이터를 추가한다.
content.append(inputLine);
}
// BufferReader 닫고
in.close();
// 카카오 서버와 연결을 끊는다.
con.disconnect();
// 결과 출력
System.out.println(content.toString());
return content;
}
}
package APITest;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Scanner;
public class KakaoAPITest {
public static void main(String[] args) throws IOException {
// 1. 입력을 받아서 어떤 책을 검색할지 작성하는 기능
// 2. 입력받은 값을 API로 보내서 결과 값 받기
// 3. JSON온 결과 값을 파싱해서 Java로 사용하기 쉽게 변경
// 4. PDF 만들기
Scanner sc = new Scanner(System.in);
while(true){
String input = sc.next();
if(input.equals("종료")){
System.out.println("프로그램을 종료합니다.");
break;
}
BookAPITest.apiCall(input);
}
}
}
package AutoTest;
// 크롤링
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.List;
public class AutoTest1 {
public static void main(String[] args) throws InterruptedException {
String url = "https://www.daum.net/";
//현재 PC에 있는 chromedriver을 가지고 와서 setup
WebDriverManager.chromedriver().setup();
// selenium -> setup이 되었기 때문에 ChromeDriver 객체를 생성
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
//웹 페이지 열기
driver.get(url);
//6초간 정지
Thread.sleep(1000);
// dirver를 이용해서 관련된 태그 추출
// findElement메소드를 사용 매개변수 By. id/css/tag/cssSelector
WebElement input = driver.findElement(By.cssSelector("input.tf_keyword"));
//위에 추출한 태그 객체에 sendKeys 키입력을 매개변수 값으로 실행
input.sendKeys("이");
//키 입력후 0.5초간 정지
Thread.sleep(500);
input.sendKeys("병");
Thread.sleep(500);
input.sendKeys("헌");
Thread.sleep(500);
input.sendKeys(" ");
Thread.sleep(500);
input.sendKeys("건");
Thread.sleep(500);
input.sendKeys("치");
Thread.sleep(500);
//input에 추출한 태그에 키보드 엔터값입력
input.sendKeys(Keys.ENTER);
//똑같은 이름에 태그가 여러개일 때 findElements를 사용
//결과 값을 List로 받아야 합니다. List가 관리하는 클래스 WebElement
List<WebElement> thumbs = driver.findElements(By.cssSelector("a.thumb_bf"));
//위 결과를 받은 List 중에 0번에 click을 실행
thumbs.get(0).click();
/*
// JavaScript명령문을 사용하기 위한 driver를 형변환
// 형변환 ->JavascriptExecutor
// JavascriptExecutor을 이용해서 웹 화면의 움직임 명령을 함
JavascriptExecutor js = (JavascriptExecutor) driver;
int move = 200;
for(int i=0;;i++){
// window.scrollTo(현재위치,다음위치) 현재위치 -> 다음위치로 내려간다.
String s = "window.scrollTo(" + move * i +","+ move * (i+1) +")";
// 위에 선언된 JavaScript 명령어 문자열을 실제로 실행
js.executeScript(s);
//1초가 정지
Thread.sleep(1000);
// move * (i+1)이 200000초과면 반복문 종료
if(move * (i+1) > 200000){
break;
}
}
*/
}
}
package ExcelTest;
// 엑셀 리더기
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExcelTest {
public static void main(String[] args) throws IOException {
//1. 엑셀 파일 읽기 FileInputStream
FileInputStream file = new FileInputStream(new File("member.xlsx"));
//2.FileInputStream -> Workbook 엑셀 읽을 수 있게 생성
Workbook workbook = WorkbookFactory.create(file);
//3.Excel -> sheet
Sheet sheet = workbook.getSheetAt(0);
//4. sheet -> row
for(Row r : sheet){
//5. row -> cell
for(Cell c : r){
if(c.getCellType() == CellType.NUMERIC){
if(DateUtil.isCellDateFormatted(c)){
//날짜
Date d = c.getDateCellValue();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = dateFormat.format(d);
System.out.print(date+"\t");
}
else{
double number = c.getNumericCellValue();
//정수
if(number == Math.floor(number)) {
System.out.print(((int)number)+"\t");
}
//실수
else{
System.out.print(number+"\t");
}
}
}
else if(c.getCellType() == CellType.STRING){
System.out.print(c.getStringCellValue()+"\t");
}
else if(c.getCellType() == CellType.BOOLEAN){
System.out.print(c.getBooleanCellValue()+"\t");
}
else if(c.getCellType() == CellType.FORMULA){
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Date d =evaluator.evaluateInCell(c).getDateCellValue();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = dateFormat.format(d);
System.out.print(date+"\t");
}
else if(c.getCellType() == CellType.BLANK){
System.out.print("\t");
}
else{
System.out.print("\t");
}
}
System.out.println();
}
}
}
package ExcelTest;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ExcelWriterTest {
public static void main(String[] args) throws IOException {
/*
private int age;
private String birthdate;
private String phone;
private String address;
private boolean isMarried;
*/
// 이름 : 호랑이
// ...
// 이름 : 강아지
// ...
// 이름 : 종료
// 탈출 하는 프로그램
// 입력을 위핸 Scanner 객체 생성
Scanner sc = new Scanner(System.in);
//ArrayList -> Member 담고 있는 객체 생성
ArrayList<Member> list = new ArrayList<Member>();
//무한 루프
while(true){
System.out.print("이름 : "); //출력
String name = sc.next(); // 입력
//name의 값이 종료이면 실행
if(name.equals("종료")){
break; //반복문 탈출
}
System.out.print("나이 : ");
int age = sc.nextInt();
sc.nextLine();
System.out.print("생년월일 : ");
String birth = sc.next();
System.out.print("전화번호 : ");
String tel = sc.next();
System.out.print("주소 : ");
String address = sc.next();
System.out.print("결혼 여부 : ");
boolean isMarred = sc.nextBoolean();
Member m = new Member(name,age,birth,tel,address,isMarred);
list.add(m);
}
for(Member m : list){
System.out.println(m);
}
//엑셀 객체 XSSFWorkbook 생성
XSSFWorkbook workbook = new XSSFWorkbook();
// sheet객체 Sheet 생성 "멤버 정보" sheet 이름
Sheet sheet = workbook.createSheet("멤버 정보");
//헤더 생성
// Row 행 생성 (0)
Row headRow = sheet.createRow(0);
// Row -> Cell 생성 -> Cell 값을 대입
headRow.createCell(0).setCellValue("이름");
headRow.createCell(1).setCellValue("나이");
headRow.createCell(2).setCellValue("생년월일");
headRow.createCell(3).setCellValue("전화번호");
headRow.createCell(4).setCellValue("주소");
headRow.createCell(5).setCellValue("결혼여부");
// 입력 받은 데이터 -> 엑셀 입력
// 행 row
for(int i = 0;i<list.size();i++){
Member m = list.get(i);
Row r = sheet.createRow(i+1); // sheet -> row 생성 인덱스는 i + 1
// 열 cell
r.createCell(0).setCellValue(m.getName()); // 행 -> cell 0 생성 -> 데이터 m.getname() 추가
r.createCell(1).setCellValue(m.getAge());
r.createCell(2).setCellValue(m.getBirthdate());
r.createCell(3).setCellValue(m.getPhone());
r.createCell(4).setCellValue(m.getAddress());
r.createCell(5).setCellValue(m.isMarried());
}
String fileName = "member.xlsx"; // 파일 이름 변수 생성 및 초기화
//FileOutputStream meber.xlsx에 쓰기 준비 완료
FileOutputStream outputStream = new FileOutputStream(new File(fileName));
//workbook을 write 메소드 호출을 하여 FileOutputStream 파일에 쓰기
workbook.write(outputStream);
//workbook 닫으면서 파일에 쓰기 완성
workbook.close();
System.out.println("엑셀 완성 : "+fileName);
}
}
package ExcelTest;
public class Member {
private String name;
private int age;
private String birthdate;
private String phone;
private String address;
private boolean isMarried;
public Member(String name, int age, String birthdate, String phone, String address, boolean isMarried) {
this.name = name;
this.age = age;
this.birthdate = birthdate;
this.phone = phone;
this.address = address;
this.isMarried = isMarried;
}
@Override
public String toString() {
return "Member{" +
"name='" + name + '\'' +
", age=" + age +
", birthdate='" + birthdate + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
", isMarried=" + isMarried +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isMarried() {
return isMarried;
}
public void setMarried(boolean married) {
isMarried = married;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>effect</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>25</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.4.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>8.0.4</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.15.0</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.5.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
</project>
오늘은 예외처리와 내부 클래스까지 배우고 크롤링과 여러가지 자바로 사용할 수 있는 기술들에 대해 활용해보는 시간을 가져보았다.
재미있었다.