변수형 long을 사용한 간단한 예제입니다.

 

Java 의 자료형 중 하나인 long 을 활용한 간단한 예제 입니다.

 

*** 원문

Vlong.java

/*
* long is 64 bit signed type and used when int is not large
* enough to hold the value.
*
* Declare long varibale as below
*
* long = ;
*
* here assigning default value is optional.
*/

 

 

 

 

*** 소스

package com.redjava.java.variable;

import java.util.Date;

public class Vlong {
 
 public static void main(String[] args) {

    long timeInMilliseconds = new Date().getTime();
       System.out.println("Time in milliseconds is : " + timeInMilliseconds);   
  
 }

}

 

 

*** 결과

Time in milliseconds is : 1353309685380

 

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

변수형 short을 사용한 간단한 예제입니다.

 

Java 의 자료형 중 하나인 short 를 활용한 간단한 예제 입니다.

 

*** 원문

Vshort.java

* short is 16 bit signed type ranges from ?32,768 to 32,767.

*
* Declare short varibale as below
* 
* short = ;
* 
* here assigning default value is optional.
*/

 

 

 

 

*** 소스

package com.redjava.java.variable;

public class Vshort {
 
 
 public static void main(String[] args) {
   short s1 = 50;
      short s2 = 42;

   System.out.println("Value of short variable b1 is :" + s1);
   System.out.println("Value of short variable b1 is :" + s2);
  
 }

}

*** 결과

Value of short variable b1 is :50
Value of short variable b1 is :42

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

변수형 boolean을 사용한 간단한 예제입니다.

 

 

Java  의 자료형중 하나인 boolean 을 사용하는 간단한 예제 입니다.

 

*** 원본설명

 

Vboolean.java


/*
* boolean is simple Java type which can have only of two values; true or false.

* All rational expressions retrun this type of value. 
*
* Declare boolean varibale as below
* 
* boolean = ;
* 
* here assigning default value is optional.
*/

 

*** 소스

 

package com.redjava.java.variable;

public class Vboolean {
 
    public static void main(String[] args) {

 

        boolean b1 = true;
        boolean b2 = false;
       
        boolean b3 = (10 > 2)? true:false;

        System.out.println("Value of boolean variable b1 is :" + b1);
        System.out.println("Value of boolean variable b2 is :" + b2);
        System.out.println("Value of boolean variable b3 is :" + b3);           


    } 

}

 

 

*** 결과

Value of boolean variable b1 is :true
Value of boolean variable b2 is :false
Value of boolean variable b3 is :true

 

 

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

HTTP POST 여러개의 파라미터를 포함한 request 테스트

 

아파치 httpclient 라이브러리를 이용하여 POST 형태로 다중 파라메터를 전송하는 예제입니다.

 

 

 

 

package com.redjava.interfaces.https;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class httpClientParams {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
    HttpClient client = new DefaultHttpClient();
      HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

      try {

        List<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>(1);
        nameValuePairs.add(new BasicNameValuePair("Email", "jsaclova"));
        nameValuePairs
            .add(new BasicNameValuePair("Passwd", "************"));
        nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
        nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
        nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
          System.out.println(line);
          if (line.startsWith("Auth=")) {
            String key = line.substring(5);
            // Do something with the key
          }

        }
      } catch (IOException e) {
        e.printStackTrace();
      }
   }


}
</namevaluepair></namevaluepair>

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

HTTP POST 여러개의 파라미터를 포함한 request 테스트

 

아파치 httpclient 라이브러리를 이용하여 POST 방식으로 페이지를 호출하는 예제입니다.

 

 

package com.redjava.interfaces.https;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class httpClientParams {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		  HttpClient client = new DefaultHttpClient();
		    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

		    try {

		      List<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>(1);
		      nameValuePairs.add(new BasicNameValuePair("Email", "jsaclova"));
		      nameValuePairs
		          .add(new BasicNameValuePair("Passwd", "************"));
		      nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
		      nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
		      nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

		      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		      HttpResponse response = client.execute(post);
		      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

		      String line = "";
		      while ((line = rd.readLine()) != null) {
		        System.out.println(line);
		        if (line.startsWith("Auth=")) {
		          String key = line.substring(5);
		          // Do something with the key
		        }

		      }
		    } catch (IOException e) {
		      e.printStackTrace();
		    }
	  }


}
블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

 

 

소켓을 통해 네트워크 정보를 보는 기본적인 예제입니다.

 

네트워크 소켓을 열어서 간단한 정보를 확인하는 예제입니다.

 

 

----------network.java-------------

package com.redjava.java.network;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class NetEcho {
 
   public static void main(String[] args) throws IOException {
   
     try {
      Socket echoSocket = new Socket("localhost", 80);
      System.out.println(echoSocket);
     }
     catch(UnknownHostException e) {
      System.err.println("Don't know about host: roseindi.");
      System.exit(1);
     }
     catch (IOException e) {
      System.err.println("I understand about "+ "the host: roseindi.");
      System.exit(1);
     }
   }

}

 

 

실행결과

 

Socket[addr=localhost/127.0.0.1,port=80,localport=51962]

 

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

 

 

도메인으로 IP 주소를 알아내는 간단한 예제소스 입니다.

 

// 변수 선언
String hostname = "www.daum.net";

// 호스트 이름으로 ip 주소값 가져오기
InetAddress ipaddress = InetAddress.getByName(hostname);

 

 

------------ network.java ---------------

package com.redjava.java.network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class NetFindIp {

   public static void main ( String[] args ) throws IOException   {
  
    String hostname = "www.daum.net";  
   
    try{   
     InetAddress ipaddress = InetAddress.getByName(hostname);
     System.out.println("IP address: " + ipaddress.getHostAddress());
     } catch ( UnknownHostException e )    {    
       System.out.println("Could not find IP address for: " + hostname);   
     }
     }
}

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,


getKeepAlive : 소켓이 살아있는지 죽었는지 확인하는 메소드

 

Server는 socket의 끊어지 상태 확인이 어려운 경우가 많으며
socket보다 방화벽의 connection timeout이 짧은 경우 종종 발생합니다.

서버는 소켓이 끊어진지 여부를 모르기 때문에 아래의 절차를 거쳐 socket close후 처리를 합니다.

if( socket.isConnected() == true && socket.getKeepAlive() == false) {
  socket.setKeepAlive(true);
  if(socket.getKeepAlive() == false) { // Socket 연결이 끊어 졌는지 확인
    socket.close();
    releaseSocket(socket, endpoint);
    socketsPool.clear(socketKey);
    socket = (Socket) socketsPool.borrowObject(socketKey);
  }
}


----- network.java ----
package com.redjava.java.network;

import java.net.*;
import java.io.*;

public class NetGetKeepAlive{
 
 public static final short TIME_PORT = 135;
 
 public static void main(String[] args) throws IOException{
  
  String hostName = null;
  System.out.println();
  
  try{
   Socket socket= new Socket(hostName,TIME_PORT);
   System.out.println("socket =" + socket);
   System.out.println("Keep Alive="+ socket.getKeepAlive());
   System.out.println("Send Buffer size ="+ socket.getSendBufferSize());
   System.out.println("output ="+socket.isOutputShutdown());
   System.out.println("port is =" + socket.getPort());
   System.out.println("socket address ="+socket.getLocalSocketAddress());
   InetAddress in= socket.getInetAddress();
   System.out.println(in);
   System.out.println("\n");
   System.out.print("RAW IP Address - (byte[]) : ");
   byte[] b1 = in.getAddress();
   
   for (int i=0; i< b1.length; i++) {
    if (i > 0) {
     System.out.print(".");}
     System.out.print(b1[i]);
   }

  }
  catch (UnknownHostException  e) {
   e.printStackTrace();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
 }
}


--- 실행결과 ---
socket =Socket[addr=localhost/127.0.0.1,port=135,localport=52195]
Keep Alive=false
Send Buffer size =8192
output =false
port is =135
socket address =/127.0.0.1:52195
localhost/127.0.0.1

RAW IP Address - (byte[]) : 127.0.0.1

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

지정된 폴더에 있는 파일들을 zip으로 압축하는 샘플 예제입니다.

 

지정된 폴더내의 모든 파일들을 zip으로 압축하는 샘플 예제

 

 // 지정된 위치에 압축파일 생성
private static final String OUTPUT_ZIP_FILE = "C:\\Workspace\\folderfile.zip";

 // 압축할 폴더 위치 지정
private static final String SOURCE_FOLDER = "C:\\Workspace";

 // ZipFolder 생성
ZipFolder ZipFolder = new ZipFolder();

 // FileOutputStream 생성
FileOutputStream fos = new FileOutputStream(zipFile);

 // ZipOutputStream 생성
ZipOutputStream zos = new ZipOutputStream(fos);

 // ZipEntry 생성
ZipEntry ze= new ZipEntry(file);

 // FileInputStream 생성
FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file);

 // 읽은 파일 쓰기
zos.write(buffer, 0, len);


---- Compression.java
package com.redjava.java.io.Compression;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolder {
 
   List<string> fileList;
   
     private static final String OUTPUT_ZIP_FILE = "C:\\Workspace\\folderfile.zip";
     private static final String SOURCE_FOLDER = "C:\\Workspace";
 
     ZipFolder(){
      fileList = new ArrayList<string>();
     }
 
     public static void main( String[] args )  {
      
      ZipFolder ZipFolder = new ZipFolder();
      ZipFolder.generateFileList(new File(SOURCE_FOLDER));
      ZipFolder.zipIt(OUTPUT_ZIP_FILE);
     }
 
     public void zipIt(String zipFile){
 
       byte[] buffer = new byte[1024];
       try{
       FileOutputStream fos = new FileOutputStream(zipFile);
       ZipOutputStream zos = new ZipOutputStream(fos);
  
       System.out.println("ZipFile : " + zipFile);
  
       for(String file : this.fileList){
        System.out.println("File 추가 : " + file);
        ZipEntry ze= new ZipEntry(file);
           zos.putNextEntry(ze);
  
           FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
  
           int len;
           while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
           }
  
           in.close();
       }
  
       zos.closeEntry();
       zos.close();
  
       System.out.println("압축이 완료되었습니다.");
   }catch(IOException ex){
      ex.printStackTrace();  
   }
    }

     public void generateFileList(File node){
   if(node.isFile()){
    fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
   }
  
   if(node.isDirectory()){
    String[] subNote = node.list();
    for(String filename : subNote){
     generateFileList(new File(node, filename));
    }
   }
 
     }

     private String generateZipEntry(String file){
      return file.substring(SOURCE_FOLDER.length()+1, file.length());
     }


}
</string></string>

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,

 

지정된 파일을 zip으로 압축하는 샘플 예제입니다

 

java 에서 지정된 파일을 zip 형태로 압축하는 샘플예제 입니다.

 

// 압축할 위치 및 압축파일명 지정
FileOutputStream fos = new FileOutputStream("C:\\Workspace\\file.zip");

 // ZipOutputStream 생성
ZipOutputStream zos = new ZipOutputStream(fos);

 // 압축할 파일명 지정
ZipEntry ze= new ZipEntry("test copy");

 // 지정한 파일명에 압축해서 넣을 압축파일 지정
zos.putNextEntry(ze);
 FileInputStream in = new FileInputStream("C:\\Workspace\\test.txt");
 
 
--- Compression.java ---
 
package com.redjava.java.io.Compression;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zip {
 
 public static void main( String[] args ){
  byte[] buffer = new byte[1024];
 
     try{
      FileOutputStream fos = new FileOutputStream("C:\\Workspace\\file.zip");
      
      ZipOutputStream zos = new ZipOutputStream(fos);
      ZipEntry ze= new ZipEntry("test copy");
      ZipEntry ze2= new ZipEntry("test1 copy");
     
      zos.putNextEntry(ze);
      FileInputStream in = new FileInputStream("C:\\Workspace\\test.txt");
 
      int len;
      while ((len = in.read(buffer)) > 0) {
       zos.write(buffer, 0, len);
      }
      in.close();
      
      zos.putNextEntry(ze2);
      FileInputStream in2 = new FileInputStream("C:\\Workspace\\test1.inf");
      
      int len2;
      while ((len2 = in2.read(buffer)) > 0) {
       zos.write(buffer, 0, len2);
      }
 
      in2.close();
 
      zos.closeEntry();
      zos.close();
 
      System.out.println("Zip 압축이 완료되었습니다.");
 
     }catch(IOException ex){
        ex.printStackTrace();
     }
 }
}

 

블로그 이미지

슬픈외로움

개발이 어려워? 모든것엔 답이있다...

,