001/*
002  Copyright 2010-2016 Boxfuse GmbH
003  <p/>
004  Licensed under the Apache License, Version 2.0 (the "License");
005  you may not use this file except in compliance with the License.
006  You may obtain a copy of the License at
007  <p/>
008  http://www.apache.org/licenses/LICENSE-2.0
009  <p/>
010  Unless required by applicable law or agreed to in writing, software
011  distributed under the License is distributed on an "AS IS" BASIS,
012  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013  See the License for the specific language governing permissions and
014  limitations under the License.
015 */
016package io.avaje.classpath.scanner.internal;
017
018import java.io.*;
019import java.nio.charset.Charset;
020import java.util.ArrayList;
021import java.util.Collections;
022import java.util.List;
023
024/**
025 * Utility class for copying files and their contents. Inspired by Spring's own.
026 */
027public class FileCopyUtils {
028  /**
029   * Prevent instantiation.
030   */
031  private FileCopyUtils() {
032    // Do nothing
033  }
034
035  public static String copyToString(InputStream inputStream, Charset charset) {
036    return copyToString(new InputStreamReader(inputStream, charset));
037  }
038
039  public static String copyToString(Reader in) {
040    StringWriter out = new StringWriter();
041    copy(in, out);
042    String str = out.toString();
043    //Strip UTF-8 BOM if necessary
044    if (str.startsWith("\ufeff")) {
045      return str.substring(1);
046    }
047    return str;
048  }
049
050  /**
051   * Copy the contents of the given Reader to the given Writer. Closes both when done.
052   */
053  private static void copy(Reader in, Writer out) {
054    try {
055      char[] buffer = new char[4096];
056      int bytesRead;
057      while ((bytesRead = in.read(buffer)) != -1) {
058        out.write(buffer, 0, bytesRead);
059      }
060      out.flush();
061    } catch (IOException e) {
062      throw new UncheckedIOException(e);
063    } finally {
064      try {
065        in.close();
066      } catch (IOException ex) {
067        //Ignore
068      }
069      try {
070        out.close();
071      } catch (IOException ex) {
072        //Ignore
073      }
074    }
075  }
076
077
078  public static List<String> readLines(InputStream inputStream, Charset charset) {
079    if (inputStream == null) {
080      return Collections.emptyList();
081    }
082    try {
083      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
084      List<String> result = new ArrayList<>();
085
086      String line;
087      while ((line = reader.readLine()) != null) {
088        result.add(line);
089      }
090      return result;
091    } catch (IOException e) {
092      throw new UncheckedIOException(e);
093    }
094  }
095}