001/**
002 *
003 * Copyright 2017 Florian Schmaus, 2018 Paul Schaub.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.ox.util;
018
019import java.io.File;
020import java.io.FileInputStream;
021import java.io.FileNotFoundException;
022import java.io.FileOutputStream;
023import java.io.IOException;
024
025public class FileUtils {
026
027    public static FileOutputStream prepareFileOutputStream(File file) throws IOException {
028        if (!file.exists()) {
029
030            // Create parent directory
031            File parent = file.getParentFile();
032            if (!parent.exists() && !parent.mkdirs()) {
033                throw new IOException("Cannot create directory " + parent.getAbsolutePath());
034            }
035
036            // Create file
037            if (!file.createNewFile()) {
038                throw new IOException("Cannot create file " + file.getAbsolutePath());
039            }
040        }
041
042        if (file.isDirectory()) {
043            throw new AssertionError("File " + file.getAbsolutePath() + " is not a file!");
044        }
045
046        return new FileOutputStream(file);
047    }
048
049    public static FileInputStream prepareFileInputStream(File file) throws IOException {
050        if (file.exists()) {
051            if (file.isFile()) {
052                return new FileInputStream(file);
053            } else {
054                throw new IOException("File " + file.getAbsolutePath() + " is not a file!");
055            }
056        } else {
057            throw new FileNotFoundException("File " + file.getAbsolutePath() + " not found.");
058        }
059    }
060}