Java tutorial
/* * Copyright (C) 2017 FormKiQ Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.formkiq.core.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; /** * Class for finding Resource(s). * */ public final class Resources { /** * Gets a file from classpath as bytes. * @param file String * @return byte[] * @throws IOException IOException */ public static byte[] getResourceAsBytes(final String file) throws IOException { InputStream is = getResourceAsInputStream(file); try { byte[] bytes = IOUtils.toByteArray(is); return bytes; } finally { IOUtils.closeQuietly(is); } } /** * Gets a file from classpath as bytes. * @param file {@link String} * @return {@link String} * @throws IOException IOException */ public static InputStream getResourceAsInputStream(final String file) throws IOException { InputStream is = null; Resource resource = new ClassPathResource(file); try { is = resource.getInputStream(); } catch (FileNotFoundException e) { // check for file in tomcat conf directory String catalinabase = System.getProperty("catalina.base"); if (StringUtils.hasText(catalinabase)) { File configDir = new File(catalinabase, "conf"); File configFile = new File(configDir, file); if (configFile.exists()) { is = new FileInputStream(configFile); } } } return is; } /** * Gets a file from classpath as bytes. * @param file {@link String} * @return {@link String} * @throws IOException IOException */ public static String getResourceAsString(final String file) throws IOException { InputStream is = getResourceAsInputStream(file); if (is == null) { throw new FileNotFoundException(file); } try { byte[] bytes = IOUtils.toByteArray(is); String s = Strings.toString(bytes); return s; } finally { IOUtils.closeQuietly(is); } } /** * private constructor. */ private Resources() { } }