001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2022, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.testUtil;
015
016import java.io.BufferedReader;
017import java.io.File;
018import java.io.FileInputStream;
019import java.io.IOException;
020import java.io.InputStream;
021import java.io.InputStreamReader;
022import java.util.Enumeration;
023import java.util.List;
024import java.util.zip.GZIPInputStream;
025import java.util.zip.ZipEntry;
026import java.util.zip.ZipFile;
027
028public class FileToBufferUtil {
029
030    static public void readIntoList(File file, List<String> stringList) throws IOException {
031
032        if (file.getName().endsWith(".gz")) {
033            gzFileReadIntoList(file, stringList);
034        } else if (file.getName().endsWith(".zip")) {
035            zipFileReadIntoList(file, stringList);
036        } else {
037            regularReadIntoList(file, stringList);
038        }
039    }
040
041    private static void zipFileReadIntoList(File file, List<String> stringList) throws IOException {
042        System.out.println("Reading zip file [" + file + "]");
043        try (ZipFile zipFile = new ZipFile(file)) {
044            Enumeration<? extends ZipEntry> entries = zipFile.entries();
045            ZipEntry entry = entries.nextElement();
046            readInputStream(zipFile.getInputStream(entry), stringList);
047        }
048    }
049
050    static void readInputStream(InputStream is, List<String> stringList) throws IOException {
051        BufferedReader in = new BufferedReader(new InputStreamReader(is));
052        String line;
053        while ((line = in.readLine()) != null) {
054            stringList.add(line);
055        }
056        in.close();
057    }
058
059    static public void regularReadIntoList(File file, List<String> stringList) throws IOException {
060        FileInputStream fis = new FileInputStream(file);
061        BufferedReader in = new BufferedReader(new InputStreamReader(fis));
062        String line;
063        while ((line = in.readLine()) != null) {
064            stringList.add(line);
065        }
066        in.close();
067    }
068
069    static public void gzFileReadIntoList(File file, List<String> stringList) throws IOException {
070        FileInputStream fis = new FileInputStream(file);
071        GZIPInputStream gzis = new GZIPInputStream(fis);
072        readInputStream(gzis, stringList);
073    }
074
075}