- 상수값에 대한 저장
- 요일
- 월~일 : 겉으로는 문자열을 사용 → 숫자상수로 저장 베이스
- API : java.util
public enum Week { //클래스를 생성하듯이 Enum생성
MONDAY, //숫자값으로 저장된다
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
import java.util.Calendar;
public class EnumEx01 {
public static void main(String[] args) {
Week today = null; //week 는 enum 타입
Calendar cal = Calendar.getInstance();
int week = cal.get(Calendar.DAY_OF_WEEK);
switch(week){
case 1:
today = Week.SUNDAY;
break;
case 2:
today = Week.MONDAY;
break;
case 3:
today = Week.TUESDAY;
break;
case 4:
today = Week.WEDNESDAY;
break;
case 5:
today = Week.THURSDAY;
break;
case 6:
today = Week.FRIDAY;
break;
case 7:
today = Week.SATURDAY;
break;
}
System.out.println("오늘 요일: " + today);
if(today.equals("THURSDAY")){ //ENUM의 비교는 문자로 하는 것이 아님
System.out.println("목요일 입니다.");
}else{
System.out.println("목요일이 아닙니다.");
}
if(today == Week.THURSDAY){ //ENUM의 비교
System.out.println("목요일 입니다.");
}else{
System.out.println("목요일이 아닙니다.");
}
}
}
2
public class EnumEx02 {
public static void main(String[] args) {
//name()
Week today = Week.SUNDAY;
String name = today.name(); //문자를 가져옴
System.out.println(name);
//ordinal()
int ordinal = today.ordinal(); //상수 값을 순번을 가져옴 0번부터 시작함
System.out.println(ordinal);
//순서 비교
Week day1 = Week.MONDAY;
Week day2 = Week.WEDNESDAY;
int result1 = day1.compareTo(day2);
int result2 = day2.compareTo(day1);
System.out.println(result1);
System.out.println(result2);
//values()
Week[] days = Week.values();
for(Week day: days){ //enum의 모든 값 가져오기
System.out.println(day);
}
}
}
3
람다식
- 메서드의 호출을 간결하게 생성한 식
- 현대 언어의 기본
- c# ~swift 에서는 람다식이 존재함
- java(x) → java 8 (o) : 자바에서는 8 부터 생김
- 오라클사에서 현대적인 언어로 변화를 시도 (sun → oracle : 자바 8)
- 람다식, Stream API, ...
- Stream - 고용량 데이터 처리 MapReduce 제공함
@FunctionalInterface //어노테이션 //람다식을 쓴다는 표시 //메소드를 2개 선언하면 에러생김
public interface MyFucntionalInterface {
//람다식을 사용하기 위한 인터페이스는 메소드르 하나만 포함함
public void method1();
//public void method2();
}
public class MyFunctionalIterfaceMain {
public static void main(String[] args) {
//기존의 인터페이스 실행방법
MyFucntionalInterface f1 = new MyFucntionalInterface() {
@Override
public void method1() {
System.out.println("call Mathod1()");
}
};
f1.method1();
//람다식 //코드가 짧아짐
MyFucntionalInterface f2 = () -> {
System.out.println("call Method1() lambda");
};
f2.method1();
//실행문 하나일때 괄호 생략가능
MyFucntionalInterface f3 = () -> System.out.println("call Method1() lambda");
;
f3.method1();
}
}
4
@FunctionalInterface
public interface MyfunctionalInterface {
//매개변수가 있는 인터페이스
public void method(int x);
}
public class MyfunctionalIterface {
public static void main(String[] args) {
//매개변수가 있는 람다식
MyfunctionalInterface f1;
f1 = (x) -> {
int result = x*5;
System.out.println(result);
};
f1.method(2);
}
}
5
@FunctionalInterface
public interface MyfunctionalInterface {
//리턴값이 있는 인터페이스
public int method(int x, int y);
}
public class MyfunctionalIterface {
public static void main(String[] args) {
//매개변수가 있는 람다식
MyfunctionalInterface f1;
f1 = (x,y)-> {
//int result = x*y;
//return result;
return x*y;
};
int result = f1.method(10, 20);
System.out.println(result);
MyfunctionalInterface f2;
f2 = (x,y) -> x*y;
int result1 = f2.method(10, 20);
System.out.println(result1);
}
}
6
public class MainEx01 {
public static void main(String[] args) {
// 쓰레드 Runnable 인터페이스 기존방식
Runnable r1 = new Runnable() {
@Override
public void run() {
for(int i =0; i<10; i++){
System.out.println(i);
}
}
};
//람다방식으로 Runnable 구현
Runnable r2 = () -> {
for(int i=0;i<10;i++){
System.out.println(i+"lambda");
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
7
외부 데이터
- web -URLConnection
- sms - 무료x
- mail -
- 자바 → 메일서버 → 메일 전송
- 일반적으로 스팸을 방지하기 위해 메일서버 개방 x
- 구글메일서버 개방되어있음
- 권한 허용 필요
- https://www.google.com/settings/security/lesssecureapps
- 자바에 메일 라이브러리 설치 필요함
//인증클래스 생성
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MyAuth extends Authenticator {
private String fromEmail;
private String password;
//생성자
public MyAuth(String fromEmail, String password) {
this.fromEmail = fromEmail;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(fromEmail, password);
}
}
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
private String fromEmail = "classic.what@gmail.com";
private String password = "패스워드";
public static void main(String[] args) {
String toEmail = "classic.what@gamil.com";
String fromName = "보내는사람은 나다";
String subject = "제목이다";
String content = "내용이다";
MailSender mail = new MailSender();
mail.sendMail(toEmail, fromName, subject, content);
}
public void sendMail(String toEmail, String fromName, String subject, String content){
try {
//메일서버 접속을 위한 환경 설정 Properties //gmail에서 제공해줌
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "stmp"); //stmp 단순메일전송규약
props.put("mail.smtp.host", "smtp.gmail.com"); //gmail 서버를 통해서 보냄
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465"); //gmail 포트번호
props.put("mail.smtp.auth", "true");
MyAuth auth = new MyAuth(fromEmail,password);
Session sess = Session.getDefaultInstance(props,auth); //세션은 접속상태 //아이디 패스워드클래스를 만들어 세션에 가져감
// 메시지
MimeMessage msg = new MimeMessage(sess);
msg.setHeader("content-type", "text/plain; charset=utf-8"); //전체데이터 규정
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail,fromName,"utf-8")); //보내는사람
msg.setSubject(subject); //제목
msg.setContent(content,"text/plain; charset=utf-8"); //내용
msg.setSentDate(new java.util.Date()); //보내는 시간
Transport.send(msg);
System.out.println("메일 전송이 완료되었습니다.");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
8
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailSender {
private String fromEmail = "classic.what@gmail.com";
private String password = "비밀번호";
public static void main(String[] args) {
String toEmail = "classic.what@gamil.com";
String fromName = "보내는사람은 나다";
String subject = "제목이다";
//html 형식으로 보내도 됨 //이미지 소스코드로 이미지 출력가능함
String content = "<html><head></head><body><font color='red'>내용이다</font><img src='http://img.naver.net/static/www/u/2013/0731/nmms_224940510.gif'></body></html>";
MailSender mail = new MailSender();
mail.sendMail(toEmail, fromName, subject, content);
}
public void sendMail(String toEmail, String fromName, String subject, String content){
try {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "stmp");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
MyAuth auth = new MyAuth(fromEmail,password);
Session sess = Session.getDefaultInstance(props,auth);
// 메시지
MimeMessage msg = new MimeMessage(sess);
msg.setHeader("content-type", "text/plain; charset=utf-8");
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail,fromName,"utf-8"));
msg.setSubject(subject);
//msg.setContent(content,"text/html; charset=utf-8"); //내용형식 html로 바꿔줌
msg.setSentDate(new java.util.Date());
// 내용 + 첨부파일
Multipart multipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("테스트용 메일입니다","utf-8");
multipart.addBodyPart(bodyPart);
bodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(new File("C:/java/workspace/MailEx/src/MyAuth.java"));
bodyPart.setDataHandler(new DataHandler(fds));
bodyPart.setFileName(fds.getName());
multipart.addBodyPart(bodyPart);
msg.setContent(multipart);
//전송
Transport.send(msg);
System.out.println("메일 전송이 완료되었습니다.");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
9. 메일보내기 GUI만들기
//인증클래스 생성
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MyAuth extends Authenticator {
private String fromEmail;
private String password;
//생성자
public MyAuth(String fromEmail, String password) {
this.fromEmail = fromEmail;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(fromEmail, password);
}
}
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.ButtonGroup;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.swing.JScrollPane;
public class MailSender extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JLabel label_1;
private JTextField textField_2;
private JTextArea textArea;
private JButton btnNewButton;
private JButton btnNewButton_1;
private final ButtonGroup buttonGroup = new ButtonGroup();
private JRadioButton rdbtnText;
private JRadioButton rdbtnHtml;
private String fromEmail = "classic.what@gmail.com";
private String password = "비밀번호";
private JScrollPane scrollPane;
private JButton btnHtml;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MailSender frame = new MailSender();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MailSender() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 486, 349);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("받는사람");
lblNewLabel.setBounds(11, 10, 57, 15);
contentPane.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(80, 7, 377, 21);
contentPane.add(textField);
textField.setColumns(10);
JLabel label = new JLabel("제목");
label.setBounds(11, 41, 57, 15);
contentPane.add(label);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(80, 38, 377, 21);
contentPane.add(textField_1);
label_1 = new JLabel("첨부");
label_1.setBounds(12, 248, 57, 15);
contentPane.add(label_1);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(81, 245, 261, 21);
contentPane.add(textField_2);
JLabel label_2 = new JLabel("형식");
label_2.setBounds(11, 73, 57, 15);
contentPane.add(label_2);
rdbtnText = new JRadioButton("Text");
rdbtnText.setSelected(true);
buttonGroup.add(rdbtnText);
rdbtnText.setBounds(80, 69, 121, 23);
contentPane.add(rdbtnText);
rdbtnHtml = new JRadioButton("HTML");
buttonGroup.add(rdbtnHtml);
rdbtnHtml.setBounds(220, 69, 90, 23);
contentPane.add(rdbtnHtml);
JLabel label_3 = new JLabel("내용");
label_3.setBounds(11, 98, 57, 15);
contentPane.add(label_3);
scrollPane = new JScrollPane();
scrollPane.setBounds(80, 98, 378, 137);
contentPane.add(scrollPane);
textArea = new JTextArea();
scrollPane.setViewportView(textArea);
btnNewButton = new JButton("첨부파일");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
//첨부 파일선택기
JFileChooser fileChooser = new JFileChooser("c:\\");
int result = fileChooser.showOpenDialog(MailSender.this);
if(result == JFileChooser.APPROVE_OPTION){
//파일경로를 텍스트 필드에 전달
textField_2.setText(fileChooser.getSelectedFile().getAbsolutePath());
}else{
System.out.println("X");
}
}
});
btnNewButton.setBounds(361, 245, 97, 23);
contentPane.add(btnNewButton);
btnNewButton_1 = new JButton("전송");
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//보낼주소 받기
String toEmail = textField.getText();
//제목 받기
String subject = textField_1.getText();
//형식 받기
String format = "";
if(rdbtnText.isSelected()){ //라디오버튼 체크되어있으면 메일보낼 형식 format에 넣음
format = "plain";
}else if(rdbtnHtml.isSelected()){
format = "html";
}
//내용받기
String content = textArea.getText();
//첨부파일주소 받기
String addFile = textField_2.getText();
//메일보내기
MailSender mail = new MailSender();
if(!toEmail.equals("")){ //메일주소값이 있어야지 메일 보냄
mail.sendMail(toEmail, "홍길동", subject, content, format, addFile);
}
dispose(); //보낸 뒤에 창 닫기
}
});
btnNewButton_1.setBounds(361, 278, 97, 23);
contentPane.add(btnNewButton_1);
btnHtml = new JButton("HTML 미리보기");
btnHtml.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//html 내용 가져오기
String htmlcont = textArea.getText();
//html 파일 생성
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("c:/java/htmlcont.html"));
bw.write(htmlcont);
System.out.println("출력완료");
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if(bw != null) try{ bw.close();} catch(IOException e1){}
}
//html 파일 열기
try {
File file = new File("c:/java/htmlcont.html");
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnHtml.setBounds(336, 69, 121, 23);
contentPane.add(btnHtml);
}
//메일보내기 메서드
public void sendMail(String toEmail, String fromName, String subject, String content, String format, String addFile){
try {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "stmp");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
MyAuth auth = new MyAuth(fromEmail,password);
Session sess = Session.getDefaultInstance(props,auth);
// 메시지
MimeMessage msg = new MimeMessage(sess);
msg.setHeader("content-type", "text/plain; charset=utf-8");
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail,fromName,"utf-8"));
msg.setSubject(subject);
msg.setSentDate(new java.util.Date());
// 내용
Multipart multipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(content,"text/"+format+"; charset=utf-8");
multipart.addBodyPart(bodyPart);
//첨부파일
if(!addFile.equals("")){ //첨부파일이 있을경우만 첨부파일 보내기
bodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(new File(addFile));
bodyPart.setDataHandler(new DataHandler(fds));
bodyPart.setFileName(fds.getName());
multipart.addBodyPart(bodyPart);
}
msg.setContent(multipart);
//전송
Transport.send(msg);
System.out.println("메일 전송이 완료되었습니다.");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
댓글 없음:
댓글 쓰기