'Java'에 해당되는 글 18건

  1. 2015.01.13 자바에서 파일을 복사하는 4가지 방법
  2. 2014.08.27 랜덤 문자열 생성
  3. 2011.06.23 Java에서 웹 브라우저 띄우기
  4. 2011.06.14 GUI 기반 Java Decompiler
  5. 2011.02.17 Java Shallow Copy and Deep Copy
  6. 2011.01.19 Java 시스템 정보 가져오기
  7. 2010.08.06 Eclipse 프로젝트 참조
2015.01.13 14:14

자바에서 파일을 복사하는 4가지 방법

1. FileStream

private static void copyFileUsingFileStreams(File source, File dest)
		throws IOException {
	InputStream input = null;
	OutputStream output = null;
	try {
		input = new FileInputStream(source);
		output = new FileOutputStream(dest);
		byte[] buf = new byte[1024];
		int bytesRead;
		while ((bytesRead = input.read(buf)) > 0) {
			output.write(buf, 0, bytesRead);
		}
	} finally {
		input.close();
		output.close();
	}
}


2. java.nio.channels.FileChannel

private static void copyFileUsingFileChannels(File source, File dest)
		throws IOException {
	FileChannel inputChannel = null;
	FileChannel outputChannel = null;
	try {
		inputChannel = new FileInputStream(source).getChannel();
		outputChannel = new FileOutputStream(dest).getChannel();
		outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
	} finally {
		inputChannel.close();
		outputChannel.close();
	}
}


3. Apache Commons IO

private static void copyFileUsingApacheCommonsIO(File source, File dest)
		throws IOException {
	FileUtils.copyFile(source, dest);
}


4. Java 7 Files class

private static void copyFileUsingJava7Files(File source, File dest)
		throws IOException {
	Files.copy(source.toPath(), dest.toPath());
}



[출처] 4 Ways to Copy File in Java

Trackback 0 Comment 0
2014.08.27 16:02

랜덤 문자열 생성

아파치의 RandomStringUtils 사용

import org.apache.commons.lang.RandomStringUtils;

public class RandomStringUtilsTest {
    int length = 10;
    String randomString = RandomStringUtils.random(length, true, true);
    System.out.println(randomString);
}


Maven Repository

http://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.3.2


	org.apache.commons
	commons-lang3
	3.3.2


[출처] 자바 (Java)에서 랜덤 (Random) 문자열 (String) 생성하기

Trackback 0 Comment 0
2011.06.23 14:01

Java에서 웹 브라우저 띄우기

import java.lang.reflect.Method;

public class BrowserControl {
	/**
	 * Method to Open the Broser with Given URL
	 * 
	 * @param url
	 */
	public static void openUrl(String url) {
		String os = System.getProperty("os.name");
		Runtime runtime = Runtime.getRuntime();
		try {
			// Block for Windows Platform
			if (os.startsWith("Windows")) {
				String cmd = "rundll32 url.dll,FileProtocolHandler " + url;
				Process p = runtime.exec(cmd);
			}
			// Block for Mac OS
			else if (os.startsWith("Mac OS")) {
				Class fileMgr = Class.forName("com.apple.eio.FileManager");
				Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
				openURL.invoke(null, new Object[] { url });
			}
			// Block for UNIX Platform
			// else {
			// String[] browsers = {"firefox", "opera", "konqueror", "epiphany",
			// "mozilla", "netscape" };
			// String browser = null;
			// for (int count = 0; count < style="color: rgb(153, 0, 0);">length
			// && browser == null; count++)
			// if (runtime.exec(new String[] {"which",
			// browsers[count]}).waitFor() == 0)
			// browser = browsers[count];
			// if (browser == null)
			// throw new Exception("Could not find web browser");
			// else
			// runtime.exec(new String[] {browser, url});
			// }
		} catch (Exception x) {
			System.err.println("Exception occurd while invoking Browser!");
			x.printStackTrace();
		}
	}

	public static void main(String[] args) {
		openUrl("http://javaxden.blogspot.com");
	}
}

윈도우에서는 뜨는거 확인했고, 맥이랑 유닉스는 확인 못했씁니다..


[출처] Launch Web Browser through Java
Trackback 0 Comment 0
2011.06.14 09:18

GUI 기반 Java Decompiler

GUI 기반의 Java Decompiler - JD-GUI



[출처] Java Decompiler

Trackback 0 Comment 0
2011.02.17 15:38

Java Shallow Copy and Deep Copy

Java provides a mechanism for creating copies of objects called cloning. There are two ways to make a copy of an object called shallow copy and deep copy.

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.

Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.

Java supports shallow and deep copy with the Cloneable interface to create copies of objects. To make a clone of a Java object, you declare that an object implements Cloneable, and then provide an override of the clone method of the standard Java Object base class. Implementing Cloneable tells the java compiler that your object is Cloneable. The cloning is actually done by the clone method.


[출처] What is shallow copy and deep copy in Java?
Trackback 0 Comment 0
2011.01.19 15:00

Java 시스템 정보 가져오기

Java에서 현재 시스템의 정보를 가져오기 위해서는 System 클래스의 getPoperty(String key) 메소드를 이용하면 된다.

                        Key                                       Description
  1   java.version   The version of Java Runtime Environment.
  2   java.vendor    The name of Java Runtime Environment vendor
  3   java.vendor.url   The URL of Java vendor
  4   java.home   The directory of Java installation 
  5   java.vm.specification.version   The specification version of Java Virtual Machine
  6   java.vm.specification.vendor   The name of specification vendor of Java Virtual Machine 
  7   java.vm.specification.name   Java Virtual Machine specification name
  8   java.vm.version    JVM implementation version
  9   java.vm.vendor   JVM implementation vendor
  10   java.vm.name    JVM  implementation name
  11   java.specification.version    The name of specification version Java Runtime Environment 
  12   java.specification.vendor   JRE specification vendor
  13   java.specification.name    JRE specification name
  14   java.class.version   Java class format version number
  15   java.class.path   Path of java class
  16   java.library.path   List of paths to search when loading libraries
  17   java.io.tmpdir   The path of temp file
  18   java.compiler   The Name of JIT compiler to use
  19   java.ext.dirs   The path of extension directory or directories
  20   os.name    The name of OS name
  21   os.arch    The OS architecture
  22   os.version    The version of OS
  23   file.separator   The File separator
  24   path.separator    The path separator 
  25   line.separator   The line separator
  26   user.name   The name of account name user
  27   user.home   The home directory of user 
  28   user.dir    The current working directory of the user


예제
public class OpertingSystemInfo {
	public static void main(String[] args) {
		String nameOS = "os.name";
		String versionOS = "os.version";
		String architectureOS = "os.arch";
		System.out.println("\n    The information about OS");
		System.out.println("\nName of the OS: " + System.getProperty(nameOS));
		System.out.println("Version of the OS: "
				+ System.getProperty(versionOS));
		System.out.println("Architecture of THe OS: "
				+ System.getProperty(architectureOS));
	}
}


[출처] Operating System Information
Trackback 0 Comment 0
2010.08.06 10:59

Eclipse 프로젝트 참조

아래와 같이 프로젝트가 2개가 있다. Lib Project는 프로젝트 참조를 하는 프로젝트 이고 Source Project는 참조가 될 프로젝트가 되겠다. 



MessagePrinter 클래스는 아래와 같이 스트링을 받아서 이를 출력하는 메소드를 가지고 있다.
package com.printer;

public class MessagePrinter {
	public void printMessage(String message) {
		System.out.println(message);
	}
}

다른 프로젝트를 참조하기 위해서는 먼저 프로젝트 참조를 추가해야 한다. 참조하고자 하는 프로젝트에서 우클릭 후 Build Path - Configure Build Path를 선택한다.




그럼 아래와 같이 Property 창이 뜬다. 여기서 Project를 선택하고 Add를 클릭~



그럼 참조가능한 프로젝트 리스트가 뜬다. 참조하고자 하는 프로젝트를 선택 후 OK



그럼 프로젝트 참조가 추가된 것을 확인할 수 있다.



자~ 이로써 준비 과정은 끝!!
클래스에서 프로젝트의 패키지를 import하고 메소드를 호출해보자.
import com.printer.*;

public class LibImport {
	
	public static void main(String[] args) {
		String testString = "Message from another project!!";
		
		MessagePrinter printer = new MessagePrinter();
		printer.printMessage(testString);
	}
}

짜잔~ 아래와 같이 정상적으로 호출 된것을 볼 수 있다.


Trackback 0 Comment 0