캠핑과 개발

java를 이용하여 텍스트 파일을 읽고 쓰는 예제입니다.

사용법은 매우 간단하지만 매번 찾아 보고 쓰게 되어 간단한 샘플을 포스팅합니다.


파일쓰기는 일반 텍스트형식과 바이너리 형식으로 쓰는 방법을 기록하며 순서는 다음과 같습니다.

1. 텍스트 파일 읽고 쓰기

2. 바이너리 파일 읽고 쓰기

3. 텍스트 파일 라인번호 읽기



1. 텍스트 파일 읽고 쓰기


  1. package test;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileReader;
  8. import java.io.FileWriter;
  9. import java.io.IOException;
  10.  
  11. public class FileTextWriteReadExample {
  12.    
  13.     public static void main(String[] args){
  14.        
  15.         File inFile = new File("C:\\Users\\Public""in.txt");
  16.         File outFile = new File("C:\\Users\\Public""in.txt");
  17.        
  18.         //==========================//
  19.         // 텍스트 파일 쓰기
  20.         //==========================//
  21.         BufferedWriter bw = null;
  22.         try {
  23.             bw = new BufferedWriter(new FileWriter(outFile));
  24.             bw.write("테스트 합니다.");
  25.             bw.newLine();
  26.             bw.write("테스트 합니다.1");
  27.             bw.flush();
  28.         } catch (IOException e) {
  29.             e.printStackTrace();
  30.         }finally {
  31.             if(bw != null) try {bw.close()} catch (IOException e) {}
  32.         }
  33.        
  34.         //==========================//
  35.         // 텍스트 파일 읽기
  36.         //==========================//
  37.         BufferedReader br = null;
  38.         try {
  39.             br = new BufferedReader(new FileReader(inFile));
  40.             String line;
  41.             while ((line = br.readLine()) != null) {
  42.                 System.out.println(line);
  43.             }
  44.         } catch (FileNotFoundException e) {
  45.             e.printStackTrace();
  46.         } catch (IOException e) {
  47.             e.printStackTrace();
  48.         }finally {
  49.             if(br != null) try {br.close()} catch (IOException e) {}
  50.         }
  51.     }
  52. }
  53.  


2. 바이너리 파일 읽기 쓰기

바이너리 파일은 알맞은 데이터형에 맞도록 쓰게되며 쓴 형식을 알지 못하면 읽는것 조차 힘듭니다.

규칙적인 형식으로 파일을 썼다면 DataInputStream객체의 available() 메서드를 이용하여 반복문으로 읽어들여서 처리할 수 있습니다.

소스 코드상에 48라인에 주석처리 되어 있습니다.


  1. package test;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.DataInputStream;
  6. import java.io.DataOutputStream;
  7. import java.io.File;
  8. import java.io.FileInputStream;
  9. import java.io.FileNotFoundException;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12.  
  13. public class FileBinaryWriteReadExample {
  14.  
  15.     public static void main(String[] args) {
  16.  
  17.         File inOutFile = new File("C:\\Users\\Public""in.bin");
  18.  
  19.         // ==========================//
  20.         // 바이너리 파일 쓰기
  21.         // ==========================//
  22.         DataOutputStream dos = null;
  23.         try {
  24.            
  25.             dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(inOutFile)));
  26.             dos.writeInt(1);
  27.             dos.writeUTF("안녕하세요");
  28.             dos.flush();
  29.        
  30.         } catch (IOException e) {
  31.             e.printStackTrace();
  32.         } finally {
  33.             if (dos != null) try { dos.close()} catch (IOException e) {}
  34.         }
  35.  
  36.         // ==========================//
  37.         // 바이너리 파일 쓰기
  38.         // ==========================//
  39.         DataInputStream dis = null;
  40.         try {
  41.            
  42.             dis = new DataInputStream(new BufferedInputStream(new FileInputStream(inOutFile)));
  43.            
  44.             System.out.println(dis.readInt());
  45.             System.out.println(dis.readUTF());
  46.            
  47.             /* 파일을 기록할 때 int 형식으로만 입력 한 경우 반복문을 통해서 읽는다.
  48.             while(dis.available() > 0){
  49.                 dis.readInt();
  50.             }*/
  51.            
  52.         } catch (FileNotFoundException e) {
  53.             e.printStackTrace();
  54.         } catch (IOException e) {
  55.             e.printStackTrace();
  56.         } finally {
  57.             if (dis != null) try {dis.close()} catch (IOException e) {}
  58.         } 
  59.     } 
  60. } 



3. 텍스트 파일 라인번호 읽기

이게 왜 필요한가 싶을지도 모르겠다. 그냥 lineCount 라는 변수를 하나 만들고 증가값을 1씩 증가하면 될텐데 말이다..

그래도 필요할지 모르니.. 일단 포스팅..


  1. package test;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.LineNumberReader;
  8.  
  9. public class FileLineNumberReaderExam {
  10.  
  11.     public static void main(String[] args) {
  12.         String path = "C:\\Users\\mjhwang\\Desktop";
  13.         String fileName = "test.txt";
  14.         LineNumberReader reader = null;
  15.         try {
  16.             reader = new LineNumberReader(new FileReader(new File(path, fileName)));
  17.             String line = null;
  18.             while ((line = reader.readLine()) != null){
  19.                 System.out.println("Line Number " + reader.getLineNumber() + " : " + line);
  20.             }
  21.         } catch (FileNotFoundException e) {
  22.             e.printStackTrace();
  23.         } catch (IOException e) {
  24.             e.printStackTrace();
  25.         }finally {
  26.             try{ if(reader != null) reader.close()}catch(IOException e){}
  27.         }
  28.     }
  29. } 


원격지의 있는 windows 10운영체제에 접속하기 위한 방법입니다.


내용은 총 다음과 같습니다.

기본적으로 1, 2 섹션만 보면 되나 경우에 따라서 3, 4번 참고하시면 됩니다.


1. 원격 데스크톱 연결 설정

2. 원격 데스크톱 방화벽 설정

3. 원격 데스크톱 포트 변경

4. 변경된 데스크톱 포트 허용



가장 먼저 원격지에서 접속하기 위해서는 해당 PC에 원격 설정 허용을 해야 합니다.


1. 원격 데스크탑 연결 설정


먼저 시스템의 원격 설정 메뉴를 선택합니다. 



원격 설정 메뉴 창이 뜨게 되면 위에 보이는 부분 처럼

항목을 체크합니다.


- 이 컴퓨터에 대한 원격 연결 허용 체크

- 네트워크 수준 인증을 사용하여 원격 데스크톱을 실행하는 컴퓨터에서만 연결 허용(권장)(N) 체크 해제 


이제는 원격 접속을 할 수 있도록 준비가 되어습니다.

원격지에서 접속을 해보시고 안되시면 아래 항목을 읽어가면서 방화벽 설정을 해주시면 됩니다. 



2. 원격 데스크탑 방화벽 허용

원격 데스크탑을 허용했다고 하여도 외부에서 접속하기 위해서는 방화벽에 해당 원격데스탑앱을 접속 가능하도록 해줘야 합니다.  



Windows 방화벽을 설정하기 위해서는 제어판으로 이동한 후 windows 방화벽 메뉴를 선택합니다.





일반적인 방화벽 초기 화면입니다. 녹색으로 표시가 되어 있으면 모든 방화벽이 동작을 하고 있는 것이며, 이 경우에는 설정된 정보에 따라서 외부에서 혹은 내부에서 들어가고 나가는 정보를 차단 혹은 허용하게 됩니다.


모든 방화벽 설정을 해제하기 위해서는 좌측 메뉴의 Windows 방화벽 설정 또는 해제에서 관리를 하면 됩니다.

방화벽 해제를 하시게 되면 기본적으로 내부에서나 외부에서 모든 접속이 허용하게 됩니다. 


여기에서는 원격데스크탑만 허용할 것이므로 Windows 방화벽을 통해 앱 또는 기능 허용 메뉴를 선택합니다. 



스크롤을 통해서 아래로 내려보면 원격 데스트톱 연결을 체크하여 방화벽에서 해당 프로그램에 접속을 허용하도록 합니다.

확인을 눌러 저장한 다음 다시 원격접속을 시도해봅니다.




3. 원격 데스크톱 포트 변경

원격 데스크탑의 기본 포트는 3389번이며 이를 변경하기 위해서는 레지스트리 편집기에서 포트값을 변경해주면 됩니다.


포트 변경을 해주기 위해서는 레지스트리를 변경해줘야 하는데 실행창에 regedit를 치시면 해당 레지스트리 편집 프로그램이 뜹니다.


좀 더 상세하게는   

Windows키 + R 키보드를 누른 후 명령창에서 regedit를 입력한 후 엔터를 누릅니다. 





regedit를 누르게 되면 정상적으로 편집기가 열리게 됩니다.

편집기가 정상적으로 실행이 되었다면 아래 경로를 찾아가는데 트리 구조이기 때문에 \로 구분하여 해당 메뉴를 찾아갑니다.

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp\PortNumber



메뉴를 따라가게 되며 최종적으로는 노란 부분의 ProtNumber까지 가게 됩니다.

해당 레지스트리 값에서 마우스를 올려놓고 우클릭을 하게 되면 메뉴가 표시가 되는데 [수정] 메뉴를 선택하여 수정 창으로 이동합니다.



처음 보여지는 값은 16진수 이므로 단위를 10진수로 변경 한 다음 값 데이터를 원하는 포트 번호로 변경하여 줍니다.

이때 사용하는 포트번호를 피하여 값을 변경해줍니다.


포트값이 다 변경이 되었다면 확인 버튼을 누르고 윈도우를 재시작 하여 줍니다.


하지만 포트만 변경이 되었다고 해서 외부에서 바로 접속 할 수 있는 것은 아닙니다. 방화벽이 모두 해제가 되어 있는 경우는 가능하나 방화벽이 동작하는 경우에는 해당 포트를 허용 신청해야 합니다. 



4. 변경된 원격 데스크톱 포트 허용  

방화벽을 통해 원격데스트탑을 허용하였지만 포트변경으로 인해 원격 데스트탑에 접속을 할 수 없는 경우에는 해당 포트를 방화벽에서 열어줘야 합니다.

이 설정은 방화벽 설정 화면에서 고급 설정 메뉴에서 가능합니다.

방화벽 설정에서 고급 설정을 선택합니다.



인바운트 규칙을 선택하신 후 우측 새 규칙을 선택합니다.


원격 지원 포트를 변경하기 위한 것으로 규칙 종류는 포트를 체크한 후 다음을 선택합니다.

다른 포트를 허용 할 경우도 동일하게 작업하시면 됩니다.



허용하고자 하는 포트를 입력한 후 다음을 선택합니다


다음을 선택합니다.



다음을 선택합니다.


해당 항목을 읽어보고 불필요한 부분은 체크 항목을 변경하도록 합니다.



새 규칙의 이름 및 설명을 입력하고 마침을 눌러 설정을 마칩니다.



이렇게 해서 원격데스트톱의 접속하기 위한 설정은 끝났습니다.


프로젝트 완료후 운영과정에서 의도하지 않은 오류가 발생했다.

문제가 된 부분은 메일 발송중에 에러가 발생했는데 흔히 메일 템플릿을 만들어 놓고 사용자명이라던지 비빌번호는 특정한 문구로 넣고 메일 발송 과정에서 해당 특정 문구를 해당 사용자의 이름과 비밀번호로 replace하여 메일을 발송하게 된다.


예를 들어 메일 템플릿에는 다음과 같은 문구가 있다.

이름 : #NAME#

비밀번호 : #PASSWORD#


해당 부분은 사용자가 메일을 받을 시점엔 다음과 같이 변경이 될것이다.

이름 : 홍길동

비밀번호 : testpassword


물론 비밀번호를 이렇게까지 표출 하는 곳은 없겠지만 예를 들어 설명한 부분이다.


일반적으로 템블릿의 특정 부분을 변경하기 위해서는 replaceAll()를 사용하게 되는데 여기에서 문제가 발생했다.

다들 신경쓰는 부분은 replaceAll(String arg1, String arg2) 메서드의 첫번째 인자를 신경쓰게 된다.

첫번째 인자는 정규표현식을 넣어야 하는데 정규표현식에서 특수문자를 문자열로 인식하기 위해서 [], \\를 감싸거나 앞에 붙여준다.


하지만 이번 문제는 2번째 인자에서 발생을 했는데 넘어가는 값은 "$0testword"와 같은 문자열이였다.

해당 문자는 소스상에서 다음과 같은 형태로 구현될것이다.


  1. String template= "비밀번호 : #PASSWORD#";
  2. String password = "$0testword";
  3.  
  4. template = template.replaceAll("#PASSWORD#", password );
  5. System.out.println(template);


정상적으로 문자열이 변경이 될것이라 생각했는데 에러가 발생을 했다.


간단하게 말하면 문제에 원인은 변경될 문자열에 "$"이 포함되어 있기 때문이다. 그리고 \\이 들어갈 경우도 의도하지 않은 결과가 발생할 수 있다.

java replaceAll 소스를 보게되면 "$", "//"일 경우 다른 처리를 하게 되므로 해당 부분을 참고하기 바란다.


이를 해결하기 위해서는 $ --> \\$로 변경하면 해결이 된다.

  1. String template= "비밀번호 : #PASSWORD#";
  2. String password = "\\$0testword";
  3.  
  4. template = template.replaceAll("#PASSWORD#", password );
  5. System.out.println(template);



replaceAll 사용시 특수문자를 치환하기 위해서는 [], \\를 쓰는데 다음과 같이 구별하여 쓴다.

[]를 사용하는 특수문자    ==> *, +, $, |, ? ==> [*]

\\를 사용하는 특수문자 ==> (, ), {, }, [, ] ==> \\(

- 를 사용하기 위해서는 \ 한번 붙여준다.

\를 사용하기 위해서는 \\를 사용한다.

한빛미디어의 JavaScript Web Applications 책을 보다보니 48page에 var 키워드 사용법이 잘못 되어 있어서 정리를 한다.

해당 책을 보게 되면 다음과 같은 내용이 있다.


키워드 var을 사용하면 전역 변수가 되므로 변수를 정의할 때 var은 절대 사용하지 않는다. 전역변수를 정의하고 싶다면 전역 영역에서 변수를 선언하거나 윈도우에서 프로퍼티로 정의한다. 


하지만 이 부분은 잘못 되었다.


var 키워드 사용여부를 떠나 전역 영역에서 변수를 선언했다면 그건 전역 변수가 된다.

그리고 함수내에서 var 키워드로 변수를 선언하면 지역 변수가 되고 var 키워드 없이 변수를 선언하게 되면 전역 변수가 된다. 


함수 내에서는 동일한 변수가 전역 변수, 지역 변수가 존재할 경우 지역 변수가 우선순위를 갖는다. 




'DEVELOPMENT > Javascript' 카테고리의 다른 글

javascript grap library  (0) 2014.03.06
HTML 우클릭 금지와 드레그 금지  (0) 2013.11.05
[Android]app <---> javascript 통신  (0) 2011.04.18
[jquery] ajax 사용하기  (0) 2010.12.17
javascript 정리  (0) 2010.12.17

HTML5의 canvas태그를 이용하여 생성된 객체를 튕기는 예제입니다.






전체소스

  1. <!DOCTYPE html>
  2. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  3. canvas {
  4.     border:1px solid #d3d3d3;
  5.     background-color: #f1f1f1;
  6. }
  7. </head>
  8. <body onload="startGame()">
  9.  
  10. var myGamePiece;
  11.  
  12. function startGame() {
  13.     myGamePiece = new component(30, 30, "red", 80, 75);
  14.     myGameArea.start();
  15. }
  16.  
  17. var myGameArea = {
  18.     canvas : document.createElement("canvas"),
  19.     start : function() {
  20.         this.canvas.width = 480;
  21.         this.canvas.height = 270;
  22.         this.context = this.canvas.getContext("2d");
  23.         document.body.insertBefore(this.canvas, document.body.childNodes[0]);
  24.         this.interval = setInterval(updateGameArea, 20);        
  25.     },
  26.     stop : function() {
  27.         clearInterval(this.interval);
  28.     },    
  29.     clear : function() {
  30.         this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  31.     }
  32. }
  33.  
  34. function component(width, height, color, x, y, type) {
  35.     this.type = type;
  36.     this.width = width;
  37.     this.height = height;
  38.     this.x = x;
  39.     this.y = y;    
  40.     this.speedX = 0;
  41.     this.speedY = 0;    
  42.     this.gravity = 0.1;
  43.     this.gravitySpeed = 0;
  44.     this.bounce = 0.6;
  45.     this.update = function() {
  46.         ctx = myGameArea.context;
  47.         ctx.fillStyle = color;
  48.         ctx.fillRect(this.x, this.y, this.width, this.height);
  49.     }
  50.     this.newPos = function() {
  51.         this.gravitySpeed += this.gravity;
  52.         this.x += this.speedX;
  53.         this.y += this.speedY + this.gravitySpeed;
  54.         this.hitBottom();
  55.     }
  56.     this.hitBottom = function() {
  57.         var rockbottom = myGameArea.canvas.height - this.height;
  58.         if (this.y > rockbottom) {
  59.             this.y = rockbottom;
  60.             this.gravitySpeed = -(this.gravitySpeed * this.bounce);
  61.         }
  62.     }
  63. }
  64.  
  65. function updateGameArea() {
  66.     myGameArea.clear();
  67.     myGamePiece.newPos();
  68.     myGamePiece.update();
  69. }
  70.  
  71.  
  72. <p>The bouncing property indicates how strong a component will bounce back, after hitting the ground.</p>
  73.  
  74. <p>Set the bouncing property to a decimal number between 0 and 1.</p>
  75.  
  76. <p>0 = no bouncing.</p>
  77. <p>1 = will bounce all the way back.</p>
  78.  
  79. </body>
  80. </html>
  81.  


http://www.w3schools.com/games/game_bouncing.asp

HTML5의 canvas태그를 이용하여 생성된 객체 중력 예제입니다.





  1. <!DOCTYPE html>
  2. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  3. canvas {
  4.     border:1px solid #d3d3d3;
  5.     background-color: #f1f1f1;
  6. }
  7. </head>
  8. <body onload="startGame()">
  9.  
  10. var myGamePiece;
  11.  
  12. function startGame() {
  13.     myGamePiece = new component(30, 30, "red", 80, 75);
  14.     myGameArea.start();
  15. }
  16.  
  17. var myGameArea = {
  18.     canvas : document.createElement("canvas"),
  19.     start : function() {
  20.         this.canvas.width = 480;
  21.         this.canvas.height = 270;
  22.         this.context = this.canvas.getContext("2d");
  23.         document.body.insertBefore(this.canvas, document.body.childNodes[0]);
  24.         this.interval = setInterval(updateGameArea, 20);        
  25.     },
  26.     stop : function() {
  27.         clearInterval(this.interval);
  28.     },    
  29.     clear : function() {
  30.         this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  31.     }
  32. }
  33.  
  34. function component(width, height, color, x, y, type) {
  35.     this.type = type;
  36.     this.width = width;
  37.     this.height = height;
  38.     this.x = x;
  39.     this.y = y;    
  40.     this.speedX = 0;
  41.     this.speedY = 0;    
  42.     this.gravity = 0.05;
  43.     this.gravitySpeed = 0;
  44.     this.update = function() {
  45.         ctx = myGameArea.context;
  46.         ctx.fillStyle = color;
  47.         ctx.fillRect(this.x, this.y, this.width, this.height);
  48.     }
  49.     this.newPos = function() {
  50.         this.gravitySpeed += this.gravity;
  51.         this.x += this.speedX;
  52.         this.y += this.speedY + this.gravitySpeed;
  53.         this.hitBottom();
  54.     }
  55.     this.hitBottom = function() {
  56.         var rockbottom = myGameArea.canvas.height - this.height;
  57.         if (this.y > rockbottom) {
  58.             this.y = rockbottom;
  59.         }
  60.     }
  61. }
  62.  
  63. function updateGameArea() {
  64.     myGameArea.clear();
  65.     myGamePiece.newPos();
  66.     myGamePiece.update();
  67. }
  68.  
  69.  
  70. <p>The red square will stop falling when it hits the floor.</p>
  71.  
  72. </body>
  73. </html>


출처 :

http://www.w3schools.com/games/game_gravity.asp

HTML5의 canvas태그를 이용하여 생성된 객체를 회전 시키는 예제입니다.


  1. <!DOCTYPE html>
  2. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  3. canvas {
  4.     border:1px solid #d3d3d3;
  5.     background-color: #f1f1f1;
  6. }
  7. </head>
  8. <body onload="startGame()">
  9.  
  10. var myGamePiece;
  11.  
  12. function startGame() {
  13.     myGamePiece = new component(30, 30, "red", 80, 75);
  14.     myGameArea.start();
  15. }
  16.  
  17. var myGameArea = {
  18.     canvas : document.createElement("canvas"),
  19.     start : function() {
  20.         this.canvas.width = 480;
  21.         this.canvas.height = 270;
  22.         this.context = this.canvas.getContext("2d");
  23.         document.body.insertBefore(this.canvas, document.body.childNodes[0]);
  24.         this.frameNo = 0;
  25.         this.interval = setInterval(updateGameArea, 20);
  26.     },
  27.     stop : function() {
  28.         clearInterval(this.interval);
  29.     },    
  30.     clear : function() {
  31.         this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  32.     }
  33. }
  34.  
  35. function component(width, height, color, x, y) {
  36.     this.width = width;
  37.     this.height = height;
  38.     this.angle = 0;
  39.     this.x = x;
  40.     this.y = y;    
  41.     this.update = function() {
  42.         ctx = myGameArea.context;
  43.         ctx.save();
  44.         ctx.translate(this.x, this.y);        
  45.         ctx.rotate(this.angle);
  46.         ctx.fillStyle = color;
  47.         ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);        
  48.         ctx.restore();    
  49.     }
  50. }
  51.  
  52. function updateGameArea() {
  53.     myGameArea.clear();
  54.     myGamePiece.angle += 1 * Math.PI / 180;    
  55.     myGamePiece.update();
  56. }
  57.  
  58.  
  59. <p>The red square will rotate one degree every time the gamearea updates (50 times per second).</p>
  60.  
  61. <p>Note: The angle property must be a radian. You can convert degrees into radians by using the formula x * Math.PI / 180</p>
  62. </body>
  63. </html>
  64.  


출처 :

http://www.w3schools.com/games/game_rotation.asp

HTML5의 canvas를 이용하여 객체를 생성한 후 해당 객체를 키보드 이벤트를 통하여 이동하는 예제입니다.

키보드의 방향키 ← → ↑↓를 이용하여 이동 할 수 이동합니다.



  1. <!DOCTYPE html>
  2. <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  3. canvas {
  4.     border:1px solid #d3d3d3;
  5.     background-color: #f1f1f1;
  6. }
  7. </head>
  8. <body onload="startGame()">
  9.  
  10. var myGamePiece;
  11.  
  12. function startGame() {
  13.     myGamePiece = new component(30, 30, "red", 225, 225);
  14.     myGameArea.start();
  15. }
  16.  
  17. var myGameArea = {
  18.     canvas : document.createElement("canvas"),
  19.     start : function() {
  20.         this.canvas.width = 480;
  21.         this.canvas.height = 270;
  22.         this.context = this.canvas.getContext("2d");
  23.         document.body.insertBefore(this.canvas, document.body.childNodes[0]);
  24.         this.frameNo = 0;
  25.         this.interval = setInterval(updateGameArea, 20);
  26.         window.addEventListener('keydown', function (e) {
  27.             e.preventDefault();
  28.             myGameArea.keys = (myGameArea.keys || []);
  29.             myGameArea.keys[e.keyCode] = (e.type == "keydown");
  30.         })
  31.         window.addEventListener('keyup', function (e) {
  32.             myGameArea.keys[e.keyCode] = (e.type == "keydown");
  33.         })
  34.     },
  35.     stop : function() {
  36.         clearInterval(this.interval);
  37.     },    
  38.     clear : function() {
  39.         this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  40.     }
  41. }
  42.  
  43. function component(width, height, color, x, y, type) {
  44.  
  45.     this.type = type;
  46.     this.width = width;
  47.     this.height = height;
  48.     this.speed = 0;
  49.     this.angle = 0;
  50.     this.moveAngle = 0;
  51.     this.x = x;
  52.     this.y = y;    
  53.     this.update = function() {
  54.         ctx = myGameArea.context;
  55.         ctx.save();
  56.         ctx.translate(this.x, this.y);
  57.         ctx.rotate(this.angle);
  58.         ctx.fillStyle = color;
  59.         ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
  60.         ctx.restore();    
  61.     }
  62.     this.newPos = function() {
  63.         this.angle += this.moveAngle * Math.PI / 180;
  64.         this.x += this.speed * Math.sin(this.angle);
  65.         this.y -= this.speed * Math.cos(this.angle);
  66.     }
  67. }
  68.  
  69. function updateGameArea() {
  70.     myGameArea.clear();
  71.     myGamePiece.moveAngle = 0;
  72.     myGamePiece.speed = 0;
  73.     if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.moveAngle = -1; }
  74.     if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.moveAngle = 1; }
  75.     if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speed= 1; }
  76.     if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speed= -1; }
  77.     myGamePiece.newPos();
  78.     myGamePiece.update();
  79. }
  80.  
  81. <p>Make sure the gamearea has focus, and use the arrow keys to move the red square around.</p>
  82.  
  83. </body>
  84. </html>
  85.  



참고 : 

http://www.w3schools.com/games/game_movement.asp

'DEVELOPMENT > HTML & CSS' 카테고리의 다른 글

[canvas] HTML5의 canvas 객체의 중력 예제  (0) 2016.06.01
[canvas] 2D를 이용한 객체 회전  (0) 2016.06.01
CSS framework  (0) 2014.01.17
[TIP] <IMG> 태그의 ALT에 줄바꿈 하기  (0) 2009.10.29
DOCTYPE.  (0) 2009.10.28

spring boot를 공부하면서 설정에 관련된 사항을 정리 해본다.


1. server 포트 변경

#80 포트로 변경

server.port=80


#랜덤 포트로 변경

server.port=0




관련사이트 :

http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

자바 웹프로젝트를 진행하면서 소스 수정이 일어날 때마다 바로 반영이 되지 않기 때문에 

톰캣을 재기동하거나, 자동으로 소스를 반영하고 톰캣을 재실행되도록 설정을 한다.


이는 너무나 일상적인 개발 방법이라 전혀 이상하지 않았지만 매우 불편하고 시간을 허비하는 일이다.

순수 JSP만 이용하여 개발을 하게 되면 이런 과정을 거치지 않겠지만 요즘은 이런 개발은 하지 않을뿐더러 객체지향적으로 설계를 하다보니

JAVA 파일 갯수는 어마하게 늘어났다. 

파일 하나 수정했을 뿐인데 톰캣을 재기동하고, 때로는 파일 하나 수정했을 뿐인데 설정에 의해서 톰캣이 자동으로 재기동 된다.


이런 과정을 줄여주는 도구가 여러가지가 있겠지만 예전에는 JRebel을 잠깐 사용했었다.

좋은 점이 있지만 무엇보다 유로로 제공되고 잠깐 동안 커뮤니티 버전을 사용했는데 지금은 제공하지 않는지 URL을 찾을수가 없었다.


이번에는 이런  기능을 무료로 제공해주는 도구가 있어서 설정 방법을 요약한다.      

이름은 spring-loaded이며 다운로드는 아래 링크를 통하여 다운로드 받을 수 있다.


- homepage : https://github.com/spring-projects/spring-loaded

- maven : http://mvnrepository.com/artifact/org.springframework/springloaded/1.2.6.RELEASE


먼저 사용을 하기 위해서는 해당 사이트에서 파일을 다운로드 한다.

파일명은 현재 기준 가장 최근 파일이 아래와 같다.


springloaded-1.2.6.RELEASE.jar


해당 파일만 다운로드 받으면 준비가 끝난다.

제법 간단하다.


파일을 다운로드 받았다면 이클립스 톰캣 서버 설정을 일부 변경해줘야 한다.

이클립스에서 해당 웹어플리케이션의 톰캣 서버를 더블 클릭하면 톰캣 설정이 화면이 뜨게 되는데

1. Publishing -> Automatically publish when resources change 항목 체크

2. Server Options 탭의 모든 체크 항목 해제

3. General Information 탭 항목의 Open launch configuration 텍스트를 클릭한다.




4. Open launch configuration 텍스트를 선택하게 되면 해당 창에서 Arguments탭을 선택하여 Vm arguments 창에 위 이미지처럼 다음 옵션을 추가해준다.


-javaagent:/Users/hmjkor/Downloads/springloaded-1.2.6.RELEASE.jar -noverify


위에서 /Users/hmjkor/Downloads 부분은 각자의 PC 환경에 따라 다르게 지정이 된다. 

springloaded-1.2.6.RELEASE.jar 파일이 저장되어 있는 경로로 지정한다.  


모든 설정이 끝나면 OK 버튼을 눌러 설정을 종료하고 서버 설정 화면에서 하단 modules 탭으로 들어가서 해당 웹 어플리케이션을 선택한 후 Editor 버튼을 선택한다.




5. Editor 버튼을 통해서 띄우진 Editor Web Module 창에서 Auto reloading enabled 체크 항목을 해제한 후 OK 버튼을 눌러 설정을 종료한다.


이로써 모든 설정은 끝났으며 java 파일을 작성한 후 테스트 해본다.




데몬 프로그램에서는 다음과 같은 형태로 실행한다.


java -javaagent:<pathTo>/springloaded-{VERSION}.jar -noverify SomeJavaClass 



springloaded-1.2.6.RELEASE.jar

springloaded-1.2.4.RELEASE.jar

springloaded-1.2.7.RELEASE.jar






6. intellij 일 경우도 방법은 비슷하다. Edit Configurations 메뉴에서 톰갯을 등록해준 후 VM options 란에 옵션을 4.절에와 같이 추가해주면 된다.



그리고 On 'Update' action, On frame deactivation 옵션을 Update classes and resources 항목을 선택해주면 된다.

Update classes and resources 항목이 보이지 않는다면 Deployment 탭으로 이동한 후  Deploy at the server startup 항목의 배포 형식이 :exploded로 설정한다.





참고사이트 : 

https://github.com/spring-projects/spring-loaded