Example usage for java.io FileInputStream close

List of usage examples for java.io FileInputStream close

Introduction

In this page you can find the example usage for java.io FileInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this file input stream and releases any system resources associated with the stream.

Usage

From source file:Main.java

public static String imgCacheRead(Context context, String cacheImgFileName) {
    int len = 1024;
    byte[] buffer = new byte[len];
    try {//from ww  w.ja  va 2 s .  c o  m
        FileInputStream fis = context.openFileInput(cacheImgFileName);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int nrb = fis.read(buffer, 0, len); // read up to len bytes
        while (nrb != -1) {
            baos.write(buffer, 0, nrb);
            nrb = fis.read(buffer, 0, len);
        }
        buffer = baos.toByteArray();
        fis.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        return new String(buffer, "utf-8");
    } catch (UnsupportedEncodingException e) {

        return null;
    }
}

From source file:com.linkedin.databus.bootstrap.utils.BootstrapAddSource.java

@SuppressWarnings("static-access")
public static Config parseArgs(String[] args) throws Exception {
    CommandLineParser cliParser = new GnuParser();

    Option helpOption = OptionBuilder.withLongOpt(HELP_OPT_LONG_NAME).withDescription("Help screen")
            .create(HELP_OPT_CHAR);// w ww  .jav  a  2s  .  com

    Option sourceIdOption = OptionBuilder.withLongOpt(SOURCE_ID_OPT_LONG_NAME)
            .withDescription("Source ID for which tables need to be added").hasArg().withArgName("Source ID")
            .create(SOURCE_ID_OPT_CHAR);

    Option sourceNameOption = OptionBuilder.withLongOpt(SOURCE_NAME_OPT_LONG_NAME)
            .withDescription("Source Name for which tables need to be added").hasArg().withArgName("Source ID")
            .create(SOURCE_NAME_OPT_CHAR);

    Option dbOption = OptionBuilder.withLongOpt(BOOTSTRAP_DB_PROPS_OPT_LONG_NAME)
            .withDescription("Bootstrap producer properties to use").hasArg().withArgName("property_file")
            .create(BOOTSTRAP_DB_PROP_OPT_CHAR);

    Option cmdLinePropsOption = OptionBuilder.withLongOpt(CMD_LINE_PROPS_OPT_LONG_NAME)
            .withDescription("Cmd line override of config properties. Semicolon separated.").hasArg()
            .withArgName("Semicolon_separated_properties").create(CMD_LINE_PROPS_OPT_CHAR);

    Option log4jPropsOption = OptionBuilder.withLongOpt(LOG4J_PROPS_OPT_LONG_NAME)
            .withDescription("Log4j properties to use").hasArg().withArgName("property_file")
            .create(LOG4J_PROPS_OPT_CHAR);

    Options options = new Options();
    options.addOption(helpOption);
    options.addOption(sourceIdOption);
    options.addOption(sourceNameOption);
    options.addOption(dbOption);
    options.addOption(cmdLinePropsOption);
    options.addOption(log4jPropsOption);

    CommandLine cmd = null;
    try {
        cmd = cliParser.parse(options, args);
    } catch (ParseException pe) {
        LOG.error("Bootstrap Physical Config: failed to parse command-line options.", pe);
        throw new RuntimeException("Bootstrap Physical Config: failed to parse command-line options.", pe);
    }

    if (cmd.hasOption(LOG4J_PROPS_OPT_CHAR)) {
        String log4jPropFile = cmd.getOptionValue(LOG4J_PROPS_OPT_CHAR);
        PropertyConfigurator.configure(log4jPropFile);
        LOG.info("Using custom logging settings from file " + log4jPropFile);
    } else {
        PatternLayout defaultLayout = new PatternLayout("%d{ISO8601} +%r [%t] (%p) {%c} %m%n");
        ConsoleAppender defaultAppender = new ConsoleAppender(defaultLayout);

        Logger.getRootLogger().removeAllAppenders();
        Logger.getRootLogger().addAppender(defaultAppender);

        LOG.info("Using default logging settings");
    }

    if (cmd.hasOption(HELP_OPT_CHAR)) {
        printCliHelp(options);
        System.exit(0);
    }

    if (!cmd.hasOption(SOURCE_ID_OPT_CHAR))
        throw new RuntimeException("Source ID is not provided");

    if (!cmd.hasOption(SOURCE_NAME_OPT_CHAR))
        throw new RuntimeException("Source Name is not provided");

    if (!cmd.hasOption(BOOTSTRAP_DB_PROP_OPT_CHAR))
        throw new RuntimeException("Bootstrap config is not provided");

    String propFile = cmd.getOptionValue(BOOTSTRAP_DB_PROP_OPT_CHAR);
    LOG.info("Loading bootstrap DB config from properties file " + propFile);

    _sBootstrapConfigProps = new Properties();
    FileInputStream f = new FileInputStream(propFile);
    try {
        _sBootstrapConfigProps.load(f);
    } finally {
        f.close();
    }
    if (cmd.hasOption(CMD_LINE_PROPS_OPT_CHAR)) {
        String cmdLinePropString = cmd.getOptionValue(CMD_LINE_PROPS_OPT_CHAR);
        updatePropsFromCmdLine(_sBootstrapConfigProps, cmdLinePropString);
    }

    int srcId = Integer.parseInt(cmd.getOptionValue(SOURCE_ID_OPT_CHAR));
    String srcName = cmd.getOptionValue(SOURCE_NAME_OPT_CHAR);

    BootstrapConfig config = new BootstrapConfig();

    ConfigLoader<BootstrapReadOnlyConfig> configLoader = new ConfigLoader<BootstrapReadOnlyConfig>("bootstrap.",
            config);

    BootstrapReadOnlyConfig staticConfig = configLoader.loadConfig(_sBootstrapConfigProps);
    Config cfg = new Config();
    cfg.setDbConfig(staticConfig);
    cfg.setSrcId(srcId);
    cfg.setSrcName(srcName);
    return cfg;
}

From source file:org.springframework.hateoas.VndErrorsMarshallingTest.java

private static String readFile(org.springframework.core.io.Resource resource) throws IOException {

    FileInputStream stream = new FileInputStream(resource.getFile());

    try {/*from   w  w w . j a v a  2s .c  o  m*/
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        return Charset.defaultCharset().decode(bb).toString();
    } finally {
        stream.close();
    }
}

From source file:cn.fql.utility.FileUtility.java

/**
 * read file to byte[] with specified file path
 *
 * @param filePath specified file path//from  w w  w  .  jav a  2s . c om
 * @return <code>byte[]</code> file content
 */
public static byte[] readFile(String filePath) {
    File infoFile = new File(filePath);
    byte[] result = null;
    if (infoFile.exists()) {
        result = new byte[(int) infoFile.length()];
        try {
            FileInputStream fis = new FileInputStream(infoFile);
            fis.read(result);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:big.zip.java

/**
 * /*  ww  w  .jav  a2  s  .  c  o m*/
 * @param fileToCompress    The file that we want to compress
 * @param fileToOutput      The zip file containing the compressed file
 * @return  True if the file was compressed and created, false when something
 * went wrong
 */
public static boolean compress(final File fileToCompress, final File fileToOutput) {
    if (fileToOutput.exists()) {
        // do the first run to delete this file
        fileToOutput.delete();
        // did this worked?
        if (fileToOutput.exists()) {
            // something went wrong, the file is still here
            System.out.println("ZIP59 - Failed to delete output file: " + fileToOutput.getAbsolutePath());
            return false;
        }
    }
    // does our file to compress exist?
    if (fileToCompress.exists() == false) {
        // we have a problem here
        System.out.println("ZIP66 - Didn't found the file to compress: " + fileToCompress.getAbsolutePath());
        return false;
    }
    // all checks are done, now it is time to do the compressing
    try {
        final OutputStream outputStream = new FileOutputStream(fileToOutput);
        ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream("zip", outputStream);
        archive.putArchiveEntry(new ZipArchiveEntry(fileToCompress.getName()));
        // create the input file stream and copy it over to the archive
        FileInputStream inputStream = new FileInputStream(fileToCompress);
        IOUtils.copy(inputStream, archive);
        // close the archive
        archive.closeArchiveEntry();
        archive.flush();
        archive.close();
        // now close the input file stream
        inputStream.close();
        // and close the output file stream too
        outputStream.flush();
        outputStream.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ArchiveException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:Main.java

public static byte[] getFileContent(String fileName) {
    FileInputStream fin = null;
    try {//  w  w w.  j  a v a 2s  .com
        fin = new FileInputStream(fileName);
        int length = fin.available();
        byte[] bytes = new byte[length];
        fin.read(bytes);
        return bytes;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (fin != null) {
                fin.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.littcore.io.util.ZipUtils.java

/**
 * ?./* w w w.j av  a  2  s.c o m*/
 * 
 * @param out ZIP?
 * @param srcFile ?
 * @param basePath 
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void zip(ZipOutputStream out, File srcFile, String basePath) throws IOException {
    if (srcFile.isDirectory()) {
        File[] files = srcFile.listFiles();

        if (files.length == 0) {
            out.putNextEntry(new ZipEntry(basePath + srcFile.getName() + "/")); //?
            out.closeEntry();
        } else {
            basePath += srcFile.getName() + "/";
            for (int i = 0; i < files.length; i++) {
                zip(out, files[i], basePath);
            }
        }

    } else {
        out.putNextEntry(new ZipEntry(basePath + srcFile.getName()));
        FileInputStream in = new FileInputStream(srcFile);
        int len;
        byte[] buf = new byte[BUFFERED_SIZE];
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

static PublicKey loadPublicKey(String file, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(file);
    FileInputStream fis = new FileInputStream(file);
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);//from   w w  w.j a v a 2 s .c o  m
    fis.close();

    // Generate Public Key.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    return publicKey;
}

From source file:Main.java

public static void post(String actionUrl, String file) {
    try {//from   w  w w.  j av  a  2  s.  c o m
        URL url = new URL(actionUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
        DataOutputStream ds = new DataOutputStream(con.getOutputStream());
        FileInputStream fStream = new FileInputStream(file);
        int bufferSize = 1024; // 1MB
        byte[] buffer = new byte[bufferSize];
        int bufferLength = 0;
        int length;
        while ((length = fStream.read(buffer)) != -1) {
            bufferLength = bufferLength + 1;
            ds.write(buffer, 0, length);
        }
        fStream.close();
        ds.flush();
        InputStream is = con.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        new String(b.toString().getBytes("ISO-8859-1"), "utf-8");
        ds.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static Bitmap getBitmapByPath(String filePath, BitmapFactory.Options opts) {
    FileInputStream fis = null;
    Bitmap bitmap = null;/*www  .j a  v  a 2  s.c o m*/
    try {
        File file = new File(filePath);
        fis = new FileInputStream(file);
        bitmap = BitmapFactory.decodeStream(fis, null, opts);
    } catch (FileNotFoundException | OutOfMemoryError e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return bitmap;
}