1 // Copyright 2017 The Bazel Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package com.google.devtools.build.android.desugar; 15 16 import com.google.common.io.ByteStreams; 17 import java.io.IOException; 18 import java.io.InputStream; 19 import java.io.OutputStream; 20 import java.nio.file.Files; 21 import java.nio.file.Path; 22 23 /** Output provider is a directory. */ 24 public class DirectoryOutputFileProvider implements OutputFileProvider { 25 26 private final Path root; 27 28 public DirectoryOutputFileProvider(Path root) { 29 this.root = root; 30 } 31 32 @Override 33 public void copyFrom(String filename, InputFileProvider inputFileProvider) throws IOException { 34 Path path = root.resolve(filename); 35 createParentFolder(path); 36 try (InputStream is = inputFileProvider.getInputStream(filename); 37 OutputStream os = Files.newOutputStream(path)) { 38 ByteStreams.copy(is, os); 39 } 40 } 41 42 @Override 43 public void write(String filename, byte[] content) throws IOException { 44 Path path = root.resolve(filename); 45 createParentFolder(path); 46 Files.write(path, content); 47 } 48 49 @Override 50 public void close() { 51 // Nothing to close 52 } 53 54 private void createParentFolder(Path path) throws IOException { 55 if (!Files.exists(path.getParent())) { 56 Files.createDirectories(path.getParent()); 57 } 58 } 59 } 60