So-net無料ブログ作成

【Java】 Stream API 勉強中 (ソース) [Java]

package application;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class FileManager {
    
    private static final Logger log = LogManager.getLogger(FileManager.class);
    private Path rootpath;
    
    public static void main(String[] args) {
        
        Path filepath = Paths.get("E:/RootDir");
        FileManager fmanager = new FileManager(filepath);
        
        Path zippath = Paths.get("E:/DestDir/save.zip");
        String[] subdirs = {"subdir1", "subdir2"};
        
        fmanager.packageOut(subdirs, zippath);
    }
    
    public FileManager(Path path) {
        rootpath = path;
    }
    
    
    public void packageOut(String[] subdirs, Path zippath) {
        
        Path[] targets = Arrays.stream(subdirs).map(subdir -> rootpath.resolve(subdir)).toArray(Path[]::new);
        Predicate<Path> selecter = path -> Arrays.stream(targets).anyMatch(target -> path.startsWith(target));
        
        try (
            Stream<Path> stream = Files.walk(rootpath);
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(zippath)));
        ) {
            stream.filter(Files::isRegularFile).filter(selecter::test).forEach(path -> entryArchive(zos, path));
        } catch(IOException e) {
            log.error("圧縮に失敗しました。");
            throw new Error(e);
        }
    }
    
    
    private void entryArchive(ZipOutputStream zos, Path target) {
        
        String entryName = rootpath.relativize(target).toString();
        ZipEntry entry = new ZipEntry(entryName);
        
        try (BufferedInputStream is = new BufferedInputStream(Files.newInputStream(target));) {
            
            zos.putNextEntry(entry);
            
            byte[] buf = new byte[1024];
            int len = 0;
            
            while ((len = is.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            
            zos.closeEntry();
            
        } catch (IOException e) {
            log.error("エントリ[{}]の圧縮に失敗しました。", entryName);
            e.printStackTrace();
        }
    }
}

コメント(0) 
共通テーマ:資格・学び

コメント 0

コメントを書く

お名前:
URL:
コメント:
画像認証:
下の画像に表示されている文字を入力してください。