JavaScript
undefindend 가 전달<script>
function showInfo(num, name, addr){
console.log(`num:${num} name:${name} addr:${addr}`);
}
showInfo(1,"유재석","압구정");
showInfo();
</script>
num:1 name:유재석 addr:압구정
num:undefined name:undefined addr:undefined
<script>
function showInfo(num=0, name="박명수", addr="이태원"){
console.log(`num:${num} name:${name} addr:${addr}`);
}
showInfo();
</script>
num:0 name:박명수 addr:이태원
... 변수명 = rest parameter<script>
function printMsgs(...args){
console.log(args);
}
printMsgs();
printMsgs("hi");
printMsgs("hi", "hello", "bye");
</script>
[]
['hi']
(3) ['hi', 'hello', 'bye']
<script>
const myObj = {
num:1,
action:function(){
console.log("어떤 동작을 수행합니다");
}
};
myObj.action();
const yourObj = {
num:2,
action(){
console.log("어떤 동작을 수행했습니다")
},
fly(){
console.log("날라 다녀요");
}
};
yourObj.fly();
</script>
어떤 동작을 수행합니다
날라 다녀요
> myObj.num
< 1
> yourObj.num
< 2
> yourObj.action()
< 어떤 동작을 수행했습니다
<script>
// 기상하는 함수
function wakeUp(callback){
setTimeout(()=>{
console.log("1. 기상 완료");
callback();
},1000);
// 기상을 완료한 후에
// callback() 함수를 호출
callback();
}
// 밥먹는 함수
function eatBreakfast(){
}
// 학교 가는 함수
function goToSchool(){
}
wakeUp(()=>{
eatBreakfast();
});
</script>
JAVA
image file
video file
mp3 file
.
.
.
➜ 2진수로 8자리로 구성된 byte 알갱이로 이루어져 있다
➜ 1byte : 총 256 가지 값
➜ 1btye 의 10진수 : 0~255 사이의 숫자
⭐ 입력과 출력
입력이란?
어떤 대상으로부터 데이터를 메모리로 읽어 들이는 것
메모리란?
프로그래밍 언어의 관점에서 변수 필드 객체 로 생각
➜ 입력과 출력을 통해서 이동하는 데이터는 byte 하나하나가 이동한다고 생각하면 된다
public static void main(String[] args) {
InputStream kdb = System.in;
try {
int code = kdb.read();
System.out.println("code:"+code);
} catch (IOException e) {
e.printStackTrace();
}
}
a (입력 후 enter)
code:97
public static void main(String[] args) {
System.out.println("main 메소드가 시작되었습니다");
// 1 byte 처리 스트림
InputStream kbd = System.in;
// 2byte 처리 스트림 (65536 가지를 표현할 수 있다) 한글 처리 가능한 객체
var isr = new InputStreamReader(kbd);
System.out.print("입력:");
try {
// InputStreamReader 객체로 입력한 문자의 code 값 읽어내기
int code = isr.read();
System.out.println("code:"+code);
char ch = (char) code;
System.out.println("char:"+ch);
} catch (IOException e) {
e.printStackTrace();
}
}
main 메소드가 시작되었습니다
입력:가
code:44032
char:가
public static void main(String[] args) {
System.out.println("main 메소드가 시작되었습니다");
// 1 byte 처리 스트림
InputStream kbd = System.in;
// 2 byte 처리 스트림 ( 65536 가지를 표현할 수 있다) 한글 처리 가능한 객체
var isr = new InputStreamReader(kbd);
// BufferedReader 의 생성자로 InputStreamReader 객체를 전달해서 객체 생성
var br = new BufferedReader(isr);
System.out.print("입력:");
try {
// 문자열 한 줄 읽어오기
String line = br.readLine();
System.out.println("line:"+line);
} catch (IOException ie) {
// TODO: handle exception
ie.printStackTrace();
}
}
main 메소드가 시작되었습니다
입력:안녕하세요
line:안녕하세요
InputStream kbd = System.in;
var isr = new InputStreamReader(kbd);
var br = new BufferedReader(isr);
⭣
// 한줄 표현
var br = new BufferReader(new InputStreamReader(System.in)));
public static void main(String[] args) {
PrintStream ps = System.out;
OutputStream os = ps;
try {
os.write(97);
os.write(98);
os.write(99);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
abc
public static void main(String[] args) {
PrintStream ps = System.out;
OutputStream os = ps;
// 2byte 처리 스트림이기 때문에 한글 처리 가능
var osw = new OutputStreamWriter(os);
try {
osw.write(97);
osw.write(98);
osw.write(99);
osw.write(44032);
osw.write("분수");
osw.write("\r\n");
osw.write("피아노");
osw.flush(); // 방출
} catch (IOException e) {
e.printStackTrace();
}
}
abc가분수
피아노
.newLine() : 운영체제에 맞는 개행기호 자동 출력 메소드public static void main(String[] args) {
PrintStream ps = System.out;
OutputStream os = ps;
var osw = new OutputStreamWriter(os);
// 좀 더 많은 문자열을 한 번에 출력 가능하고 개행기호를 출력하는 기능도 가지고 있는 BufferedWritter
var bw = new BufferedWriter(osw);
try {
bw.write("하나");
bw.newLine();
bw.write("두울");
bw.newLine();
bw.write("세엣");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
하나
두울
세엣
⭐ 1byte 처리 Stream, 일반 파일을 입출력하기에 적합한 객체
InputStream ⟷ OutputStream
➜ 문자열을 처리하기에는 기능이 부족
⭐ 한글을 포함한 문자열을 처리하기에 적합한 객체
InputStreamReader ⟷ OutputStreamWriter
BufferedReader ⟷ BufferWriter
FileWriter : 파일에 문자열 출력을 도와주는 객체
public static void main(String[] args) {
String msg = """
안녕하세요
반갑습니다
수고하셨습니다
""";
File f = new File("memo.txt");
try {
// 만일 해당 파일이 존재하지 않으면
if(!f.exists()) {
// 새로 만들기
f.createNewFile();
System.out.println("memo.txt 파일을 만들었습니다");
}
// 파일에 문자열을 출력하는 기능을 가지고 있는 객체 생성
// defulat 값은 false
var fw = new FileWriter(f, true); // 문자열 두 번 생성
fw.append(msg); // append() 메소드를 이용해서 문자열 출력하기
fw.flush();
fw.close();
System.out.println("memo.txt 파일에 문자열을 기록 했습니다");
} catch (IOException ie) {
ie.printStackTrace();
}
}
// git bash로 확인
$ cat memo.txt
------------------------
안녕하세요
반갑습니다
수고하셨습니다
⭐ String은 CharSequence type 이기도 하기 때문에
append(CharSequenc csq) 에 String type을 전달 가능
FileReader : 파일에 문자열을 읽어오도록 도와주는 객체public static void main(String[] args) {
File f = new File("memo.txt");
try {
// 파일로부터 문자열을 읽어들일 수 있는 객체 생성
var fr = new FileReader(f);
// 무한 루프 돌면서
while(true) {
// 한글자씩 읽어들인다(문자의 code 값)
int code = fr.read();
// 만일 더 이상 읽을 문자가 없다면
if(code==-1) break; // 반복문 탈출
// code 를 문자로 변환
char ch = (char)code;
// 출력
System.out.println(ch);
}
} catch (Exception e) {
e.printStackTrace();
}
}
안
녕
하
세
요
반
갑
습
니
다
.
.
.
public static void main(String[] args) {
File f = new File("memo.txt");
try {
var fr = new FileReader(f);
// 좀 더 좋은 기능을 가지고 이는 BufferedReader 객체 생성
var br = new BufferedReader(fr);
while(true) {
// 한줄씩 읽어낸다 (1줄의 기준은 개행기호)
String line = br.readLine();
// 더 이상 읽을 line 이 없으면 반복문 탈출
if(line == null) break;
// 읽을 문자열 출력하기
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
안녕하세요
반갑습니다
수고하셨습니다
안녕하세요
반갑습니다
수고하셨습니다
안녕하세요
반갑습니다
수고하셨습니다
안녕하세요
반갑습니다
수고하셨습니다
hi
bye
안녕하세요
반갑습니다
수고하셨습니다
hi
bye
public static void main(String[] args) {
// 문자열을 누적시킬 객체
var sb = new StringBuffer();
File f = new File("memo.txt");
try {
var fr = new FileReader(f);
var br = new BufferedReader(fr);
while(true) {
String line = br.readLine();
if(line == null) break;
// 읽을 문자열을 StringBuffer 객체에 누적 시키기
sb.append(line);
sb.append("\r \n"); // 개행기호
}
} catch (Exception e) {
e.printStackTrace();
}
// StringBuffer 에 누적될 문자열을 String type 으로 얻어내기
String result = sb.toString();
System.out.println(result);
}
안녕하세요
반갑습니다
수고하셨습니다
.
.
.
hi
bye
public static void main(String[] args) {
try {
// 파일로부터 byte 알갱이를 읽어들일 객체 생성
var fis = new FileInputStream("C:/playground/SouthKorea.png");
// byte 알갱이를 파일에 출력할 객체 생성
var fos = new FileOutputStream("C:/playground/copied.png");
// 반복문 돌면서
while(true){
// 1 byte 씩 읽어들여서
int readedByte = fis.read();
System.out.println(readedByte);
// 만일 더 이상 읽을게 없다면 반복문 탈출
if(readedByte == -1) break;
// 읽은 byte 를 출력
fos.write(readedByte);
fos.flush();
}
System.out.println("파일 copy 완료");
// 마무리 작업
fos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
// 파일로부터 byte 알갱이를 읽어들일 객체 생성
var fis = new FileInputStream("C:/playground/SouthKorea.png");
// byte 알갱이를 파일에 출력할 객체 생성
var fos = new FileOutputStream("C:/playground/copied2.png");
// byte 알갱이 1024 개를 한 번에 읽어들일 수 있는 배열 객체 생성 (1 kilo byte)
byte[] buffer = new byte[1024];
// 반복문 돌면서
while(true){
// byte[] 객체를 전달해서 배열에 읽어들이도록 하고 몇 byte 를 읽어 들였는지를 리턴받는다
int readedCount= fis.read(buffer);
// 만일 더 이상 읽을 byte 가 없다면 반복문 탈출
if(readedCount == -1) break;
// 배열 안에 읽어들인 데이터를 읽은 갯수 만큼 출력하기
fos.write(buffer, 0, readedCount);
fos.flush();
}
System.out.println("파일 copy 완료");
// 마무리 작업
fos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 필요한 객체를 담을 변수를 미리 생성
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// 파일로부터 byte 알갱이를 읽어들일 객체 생성
fis = new FileInputStream("C:/playground/SouthKorea.png");
// byte 알갱이를 파일에 출력할 객체 생성
fos = new FileOutputStream("C:/playground/copied3.png");
// byte 알갱이 1024 개를 한 번에 읽어들일 수 있는 배열 객체 생성 (1 kilo byte)
byte[] buffer = new byte[1024];
// 반복문 돌면서
while(true){
// byte[] 객체를 전달해서 배열에 읽어들이도록 하고 몇 byte 를 읽어 들였는지를 리턴받는다
int readedCount= fis.read(buffer);
// 만일 더 이상 읽을 byte 가 없다면 반복문 탈출
if(readedCount == -1) break;
// 배열 안에 읽어들인 데이터를 읽은 갯수 만큼 출력하기
fos.write(buffer, 0, readedCount);
fos.flush();
}
System.out.println("파일 copy 완료");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fos != null) fos.close();
if(fis != null) fis.close();
} catch (Exception e) {}
}
}
close() 호출이 자동화public static void main(String[] args) {
try(
var fis = new FileInputStream("C:/playground/SouthKorea.png");
var fos = new FileOutputStream("C:/playground/copied4.png");
) {
// byte 알갱이 1024 개를 한 번에 읽어들일 수 있는 배열 객체 생성 (1 kilo byte)
byte[] buffer = new byte[1024];
// 반복문 돌면서
while(true){
// byte[] 객체를 전달해서 배열에 읽어들이도록 하고 몇 byte 를 읽어 들는지를 리턴받는다
int readedCount= fis.read(buffer);
// 만일 더 이상 읽을 byte 가 없다면 반복문 탈출
if(readedCount == -1) break;
// 배열 안에 읽어들인 데이터를 읽은 갯수 만큼 출력하기
fos.write(buffer, 0, readedCount);
fos.flush();
}
System.out.println("파일 copy 완료");
} catch (Exception e) {
e.printStackTrace();
}
}
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem saveAsItem = new JMenuItem("Save As");
JTextArea ta = new JTextArea();
전체 코드
public class MemoFrame extends JFrame{
// 필요한 필드 정의하기
JTextArea ta = new JTextArea();
// 현재 열린 파일 객체를 저장할 필드
File openedFile;
// 생성자
public MemoFrame(String title) {
super(title);
// 메뉴바
JMenuBar mb = new JMenuBar();
// 메뉴
JMenu menu = new JMenu("File");
// 메뉴 아이템
JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem saveAsItem = new JMenuItem("Save As");
// 처음에 저장 기능은 disable 된 상태로 만든다
saveItem.setEnabled(false); // 비활설화 상태
saveAsItem.setEnabled(false);
// 메뉴에 메뉴 아이템을 순서대로 추가
menu.add(newItem);
menu.add(openItem);
menu.add(saveItem);
menu.add(saveAsItem);
// 메뉴를 메뉴바에 추가
mb.add(menu);
// 프레임의 메소드를 이용해서 메뉴바를 추가하기
setJMenuBar(mb);
// 레이아웃 설정
setLayout(new BorderLayout());
// 스크롤 설정
JScrollPane scp = new JScrollPane(ta);
// 프레임의 가운데 JScrollPane 을 배치
add(scp, BorderLayout.CENTER);
// JTextArea 의 글자크기 조잘
Font font = new Font("Serif", Font.PLAIN, 30);
ta.setFont(font);
ta.setVisible(false); // 처음에는 JTextArea 를 안 보이게 설정
// new 를 눌렀을때
newItem.addActionListener((e)->{
ta.setVisible(true);
// 프레임의 제목 바꾸기
setTitle("제목 없음");
saveAsItem.setEnabled(true);
});
// Save As 를 눌렀을 때
saveAsItem.addActionListener((e)->{
// 파일 선택을 하게 해주는 객체 생성
var fc = new JFileChooser();
// 파일을 저장하게 하는 다이얼로그 띄우기
int result = fc.showOpenDialog(this);
// 만일 제대로 파일을 만들 준비를 했다면
if(result == JFileChooser.APPROVE_OPTION) {
// 해당 File 객체를 얻어오기
openedFile = fc.getSelectedFile();
// 프레임의 title 로 파일명을 출려
setTitle(openedFile.getName());
// 실제로 해당 파일 만들기
try {
openedFile.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
// 파일에 저장하는 메소드 호출
saveToFile();
}
});
}
// 현재까지 JTextArea 에 입력한 내용을 읽어와서 openedFile 에 저장하는 메소드
public void saveToFile() {
// JTextArea 에 입력한 문자열을 읽어와서
String memo = ta.getText();
// FileWritter 객체를 이용해서 openedFile 객체에 문자열이 저장되도록 한다
try (
var fw = new FileWriter(openedFile);
){
fw.append(memo);
fw.flush();
JOptionPane.showMessageDialog(this, "저장 완료");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MemoFrame f = new MemoFrame("나의 프레임");
f.setBounds(100,100,500,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}