Math.pow() 

: 제곱을 계산하는 함수 

 

사용방법

Math.power(double, double)

첫번째인자 :  값

두번째 인자 : 지수

public class test {
	public static void main(String[] args) {
		System.out.println(Math.pow(8,2));
        System.out.println((int)Math.pow(8,2));
	}
}

※ Math.pow()는 Double(실수형)타입으로 반환하기 때문에 정수형으로 사용 시 int로 형변환를 해서 사용

 

 

[결과]

Gson이란?

- Java에서 Json을 파싱하고, 생성하기 위해 사용되는 구글에서 개발한 오픈소스

- Java Object -> Json 문자열로 변환할 수 있고, Json 문자열 -> Java Object로 변환할 수 있다.

 

Gson 라이브러리 추가

1. Maven

https://mvnrepository.com/artifact/com.google.code.gson/gson

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

pom.xml에 dependency를 추가한다.

 

2. 직접 jar 추가

https://repo1.maven.org/maven2/com/google/code/gson/gson/

 

 JSON Array -> List 변환

sample.java

public class Sample {

    private String id;
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Sample [id=" + id + ", name=" + name]";
    }

 

JsonArraytoList.java

 

import com.google.gson.Gson;

public class JsonArraytoList {

    public static void main(String[] args) {

        Gson gson = new Gson();
        String json = "[{'id':'test1','name':'Kim'}, {'id':'test2','name':'Won'}]";
     
        Sample[] array = gson.fromJson(json, Sample[].class);
        List<Sample> list = Arrays.asList(array);
        
        // 결과 출력
        System.out.println(list);
    }
}

 

 

결과

[Sample [id=test1, name=Kim], Sample [id=test2, name=Won]]

자바 File클래스에  listFiles() 메서드를 사용하여 모든 파일 정보를 가져와 다른 디렉토리에 복사하려고 한다.

 

재귀적으로 호출하여 하위 디렉토리부터 상위폴더로 올라가면서 파일을 복사하여 특정 경로에 폴더에 모든 파일을 복사하여 지정 경로에 파일을 복사하려고 한다.

 

[사용방법]

copyDir(File sourceF, File targetF);
public void copyDir(File sourceF, File targetF){
    File[] target = sourceF.listFiles();
    for (File file : target) {
        File temp = new File(targetF.getAbsolutePath() + File.separator + file.getName());
        if(file.isDirectory()){
            temp.mkdir();
            copyDir(file, temp);
        } else {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(file);
                fos = new FileOutputStream(temp) ;
                byte[] b = new byte[4096];
                int cnt = 0;
                while((cnt=fis.read(b)) != -1){
                    fos.write(b, 0, cnt);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                try {
                    fis.close();
                    fos.close();
                } catch (IOException e) {
                    LOGGER.error("{}", e);
                }
            }
        }
      }
}

 

 

[참고]

[Java] 자바로 폴더(디렉토리),파일 복사하기 (tistory.com)

 

[Java] 자바로 폴더(디렉토리),파일 복사하기

자바 File클래스에는 폴더에있는 모든 파일정보를 가지고 오는 메서드인 listFiles()라는 메서드가 존재합니다. 이 listFiles() 메서드와 File클래스의 파일생성 메서드인 mkdir()를 활용하면 쉽게 파일을

coding-factory.tistory.com

 

자바에서 WatchService라는 기능을 사용하여 특정 디렉토리를 모니터링하여 디렉토리(폴더)에 파일이 생성,변경,삭제 되는 것을 감시하고 있다가 'test'라는 파일명으로 파일이 생성되면 해당 파일 정보를 출력하는 프로그램을 만들려고 한다.

 

import java.io.File;
import java.io.IOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class watchService {

    public Boolean isStart = true;

    public static void main(String[] args) {
    	Path path = Paths.get("C:\\sample");
        try {
            System.out.println("WatchService START");
            monitoring(path);
            System.out.println("WatchService END");
        } catch (IOException | InterruptedException e) {
        	System.out.println(e);
        }
    }

    private static WatchService watchService;
    private static WatchKey watchKey;
    private final static Map<WatchKey, Path> directories = new HashMap<>();

    private static void registerTree(Path start) throws IOException {
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                WatchKey key = dir.register(watchService
                		, StandardWatchEventKinds.ENTRY_CREATE //생성
                		, StandardWatchEventKinds.ENTRY_MODIFY //변경
                		, StandardWatchEventKinds.ENTRY_DELETE); //삭제
                directories.put(key, dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    public static void monitoring(Path watchPath) throws IOException, InterruptedException,ClosedWatchServiceException {
    	System.out.println("monitoring START");
        watchService = FileSystems.getDefault().newWatchService(); // watchService 생성
        registerTree(watchPath);

        //Thread thread = new Thread(() -> {
            while (true) {
                try {
                    watchKey = watchService.take(); // 이벤트가 오길 대기(Blocking)
                } catch (InterruptedException e) {
                	System.out.println(e);
                }catch(ClosedWatchServiceException e){
                	return; 
                	//LOGGER.error("{}", e);
                }
                Path dir = directories.get(watchKey);
                if (dir == null) {
                	System.out.println("WatchKey not recognized!!");
                    continue;
                }

                for (WatchEvent<?> watchEvent : watchKey.pollEvents()) { // 이벤트들을 가져옴
                    Kind<?> kind = watchEvent.kind(); // 이벤트 종류
                    WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    Path filename = watchEventPath.context();

                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        Path directory_path = directories.get(watchKey);
                        Path child = directory_path.resolve(filename);
                        File file = child.toFile();

                        if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) {
                            try {
                                registerTree(child);
                            } catch (IOException e) {
                            	System.out.println(e);
                            }
                        }

                        // 파일 확인
                        if (file.isFile() && file.getName().matches(".*test.*")) {
                    		System.out.println("===========================================================");
                    		System.out.println("파일 발견 : " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.KOREA).format(new java.util.Date()));
                    		System.out.println("파일명 : "+file.getName());
                    		System.out.println("파일경로 : "+file.getParent());
                    		System.out.println("-----------------------------------------------------------");
                        	
                        }


                    } else if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) {
                    	System.out.println("delete something in directory");
                    } else if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
                    	System.out.println("modify something in directory");
                    } else if (kind.equals(StandardWatchEventKinds.OVERFLOW)) {
                    	System.out.println("overflow");
                        continue;
                    } else {
                    	System.out.println("test");
                    }
                }

                boolean valid = watchKey.reset();
                if (!valid) {
                	directories.remove(watchKey);

                    if (directories.isEmpty()) {
                        break;
                    }
                }
            }
            try {
            	System.out.println("WatchService close");
				watchService.close();
			} catch (IOException e) {
				System.out.println(e);
			}
       // });
       // thread.start();
        System.out.println("monitoring END");
    }

  

}

 

위에 소스를 돌려보면 'test'가 들어간 파일이 특정 경로에 생성될 때 아래와 같은 로그가 콘솔에 찍히는 것을 확인할 수 있다.

 

[결과]

+ Recent posts