Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.amazonaws.codedeploy.AWSCodeDeployPublisher.java

private RevisionLocation zipAndUpload(AWSClients aws, String projectName, FilePath sourceDirectory)
        throws IOException, InterruptedException, IllegalArgumentException {

    File zipFile = null;//from ww w.j  a va 2 s .c o m
    File versionFile;
    versionFile = new File(sourceDirectory + "/" + versionFileName);

    InputStreamReader reader = null;
    String version = null;
    try {
        reader = new InputStreamReader(new FileInputStream(versionFile), "UTF-8");
        char[] chars = new char[(int) versionFile.length() - 1];
        reader.read(chars);
        version = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }

    if (version != null) {
        zipFile = new File("/tmp/" + projectName + "-" + version + ".zip");
        final boolean fileCreated = zipFile.createNewFile();
        if (!fileCreated) {
            logger.println("File already exists, overwriting: " + zipFile.getPath());
        }
    } else {
        zipFile = File.createTempFile(projectName + "-", ".zip");
    }

    String key;
    File appspec;
    File dest;
    String deploymentGroupName = getDeploymentGroupNameFromEnv();
    String prefix = getS3PrefixFromEnv();
    String bucket = getS3BucketFromEnv();

    if (bucket.indexOf("/") > 0) {
        throw new IllegalArgumentException(
                "S3 Bucket field cannot contain any subdirectories.  Bucket name only!");
    }

    try {
        if (this.deploymentGroupAppspec) {
            appspec = new File(sourceDirectory + "/appspec." + deploymentGroupName + ".yml");
            if (appspec.exists()) {
                dest = new File(sourceDirectory + "/appspec.yml");
                FileUtils.copyFile(appspec, dest);
                logger.println("Use appspec." + deploymentGroupName + ".yml");
            }
            if (!appspec.exists()) {
                throw new IllegalArgumentException(
                        "/appspec." + deploymentGroupName + ".yml file does not exist");
            }

        }

        logger.println("Zipping files into " + zipFile.getAbsolutePath());

        FileOutputStream outputStream = new FileOutputStream(zipFile);
        try {
            sourceDirectory.zip(outputStream, new DirScanner.Glob(this.includes, this.excludes));
        } finally {
            outputStream.close();
        }

        if (prefix.isEmpty()) {
            key = zipFile.getName();
        } else {
            key = Util.replaceMacro(prefix, envVars);
            if (prefix.endsWith("/")) {
                key += zipFile.getName();
            } else {
                key += "/" + zipFile.getName();
            }
        }
        logger.println("Uploading zip to s3://" + bucket + "/" + key);
        PutObjectResult s3result = aws.s3.putObject(bucket, key, zipFile);

        S3Location s3Location = new S3Location();
        s3Location.setBucket(bucket);
        s3Location.setKey(key);
        s3Location.setBundleType(BundleType.Zip);
        s3Location.setETag(s3result.getETag());

        RevisionLocation revisionLocation = new RevisionLocation();
        revisionLocation.setRevisionType(RevisionLocationType.S3);
        revisionLocation.setS3Location(s3Location);

        return revisionLocation;
    } finally {
        final boolean deleted = zipFile.delete();
        if (!deleted) {
            logger.println("Failed to clean up file " + zipFile.getPath());
        }
    }
}

From source file:com.sds.acube.ndisc.xadmin.XNDiscAdminUtil.java

/**
 * XNDisc Admin ? ?//from  w w w  .  ja va2 s.  co m
 */
private static void readVersionFromFile() {
    XNDiscAdmin_PublishingVersion = "<unknown>";
    XNDiscAdmin_PublishingDate = "<unknown>";
    InputStreamReader isr = null;
    LineNumberReader lnr = null;
    try {
        isr = new InputStreamReader(
                XNDiscAdminUtil.class.getResourceAsStream("/com/sds/acube/ndisc/xadmin/version.txt"));
        if (isr != null) {
            lnr = new LineNumberReader(isr);
            String line = null;
            do {
                line = lnr.readLine();
                if (line != null) {
                    if (line.startsWith("Publishing-Version=")) {
                        XNDiscAdmin_PublishingVersion = line
                                .substring("Publishing-Version=".length(), line.length()).trim();
                    } else if (line.startsWith("Publishing-Date=")) {
                        XNDiscAdmin_PublishingDate = line.substring("Publishing-Date=".length(), line.length())
                                .trim();
                    }
                }
            } while (line != null);
            lnr.close();
        }
    } catch (IOException ioe) {
        XNDiscAdmin_PublishingVersion = "<unknown>";
        XNDiscAdmin_PublishingDate = "<unknown>";
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
            if (isr != null) {
                isr.close();
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:com.ibm.iot.auto.bluemix.samples.ui.Configuration.java

public Configuration(String configFileName) throws JSONException, IOException {
    File configFile = null;/* w w w .  j a  v a 2s. c om*/
    FileInputStream fileInputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    try {
        configFile = new File(configFileName);
        fileInputStream = new FileInputStream(configFile);
        inputStreamReader = new InputStreamReader(fileInputStream);
        bufferedReader = new BufferedReader(inputStreamReader);
        String jsonString = "";
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            jsonString += line;
        }
        JSONObject jsonObject = new JSONObject(jsonString);
        this.apiBaseUrl = jsonObject.getString("api");
        this.tenantId = jsonObject.getString("tenant_id");
        this.userName = jsonObject.getString("username");
        this.password = jsonObject.getString("password");
    } finally {
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        if (inputStreamReader != null) {
            inputStreamReader.close();
        }
        if (fileInputStream != null) {
            fileInputStream.close();
        }
    }
}

From source file:com.anjalimacwan.MainActivity.java

public String loadNote(String filename) throws IOException {

    // Initialize StringBuilder which will contain note
    StringBuilder note = new StringBuilder("");

    // Open the file on disk
    FileInputStream input = openFileInput(filename);
    InputStreamReader reader = new InputStreamReader(input);
    BufferedReader buffer = new BufferedReader(reader);

    // Load the file
    String line = buffer.readLine();
    while (line != null) {
        note.append(line);//from   w  w  w .jav  a 2s. co m
        line = buffer.readLine();
        if (line != null)
            note.append("\n");
    }

    // Close file on disk
    reader.close();

    return (note.toString());
}

From source file:com.bstek.dorado.view.config.attachment.AttachedResourceManager.java

protected Object parseContent(Resource resource) throws Exception {
    InputStream in = resource.getInputStream();
    try {//from   w w w .  j a  va  2s.  c o  m
        InputStreamReader reader;
        if (StringUtils.isNotEmpty(charset)) {
            reader = new InputStreamReader(in, charset);
        } else {
            reader = new InputStreamReader(in);
        }
        BufferedReader br = new BufferedReader(reader);

        List<Object> sections = new ArrayList<Object>();
        boolean hasExpression = false;
        int length = 0;
        String line;
        while ((line = br.readLine()) != null) {
            if (supportsExpression) {
                Expression expression = expressionHandler.compile(line);
                if (expression != null) {
                    sections.add(expression);
                    hasExpression = true;
                    continue;
                }
            }
            sections.add(line);
            length += line.length();
        }

        br.close();
        reader.close();

        if (hasExpression) {
            return new CombinedExpression(sections);
        } else {
            StringBuffer buf = new StringBuffer(length + sections.size());
            for (Object l : sections) {
                buf.append((String) l).append('\n');
            }
            return buf.toString();
        }
    } finally {
        in.close();
    }
}

From source file:descriptordump.Main.java

public void start(String args[]) throws DecoderException, ParseException {
    File inputFile = null;// w ww  .  j  a  v a  2 s .  c  o  m
    Charset cs = null;

    final Option charSetOption = Option.builder("c").required(false).longOpt("charset").desc(
            "?????????????")
            .hasArg().type(String.class).build();

    final Option fileNameOption = Option.builder("f").required().longOpt("filename")
            .desc("??").hasArg().type(String.class).build();

    Options opts = new Options();
    opts.addOption(fileNameOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();
    try {
        cl = parser.parse(opts, args);

        try {
            cs = Charset.forName(cl.getOptionValue(charSetOption.getOpt()));
        } catch (Exception e) {
            LOG.error(
                    "?????????",
                    e);
            cs = Charset.defaultCharset();
        }
        inputFile = new File(cl.getOptionValue(fileNameOption.getOpt()));
        if (!inputFile.isFile()) {
            throw new ParseException("?????????");
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
    }

    final Set<TABLE_ID> tids = new HashSet<>();
    tids.add(TABLE_ID.SDT_THIS_STREAM);
    tids.add(TABLE_ID.SDT_OTHER_STREAM);
    tids.add(TABLE_ID.NIT_THIS_NETWORK);
    tids.add(TABLE_ID.NIT_OTHER_NETWORK);
    tids.add(TABLE_ID.EIT_THIS_STREAM_8_DAYS);
    tids.add(TABLE_ID.EIT_THIS_STREAM_NOW_AND_NEXT);
    tids.add(TABLE_ID.EIT_OTHER_STREAM_8_DAYS);
    tids.add(TABLE_ID.EIT_OTHER_STREAM_NOW_AND_NEXT);

    LOG.info("Starting application...");
    LOG.info("ts filename   : " + inputFile.getAbsolutePath());
    LOG.info("charset       : " + cs);

    Set<Section> sections = new HashSet<>();
    try {
        FileInputStream input = new FileInputStream(inputFile);
        InputStreamReader stream = new InputStreamReader(input, cs);
        BufferedReader buffer = new BufferedReader(stream);

        String line;
        long lines = 0;
        while ((line = buffer.readLine()) != null) {
            byte[] b = Hex.decodeHex(line.toCharArray());
            Section s = new Section(b);
            if (s.checkCRC() == CRC_STATUS.NO_CRC_ERROR && tids.contains(s.getTable_id_const())) {
                sections.add(s);
                LOG.trace("1????");
            } else {
                LOG.error("?????? = " + s);
            }
            lines++;
        }
        LOG.info(
                "?? = " + lines + " ? = " + sections.size());
        input.close();
        stream.close();
        buffer.close();
    } catch (FileNotFoundException ex) {
        LOG.fatal("???????", ex);
    } catch (IOException ex) {
        LOG.fatal("???????", ex);
    }

    SdtDescGetter sde = new SdtDescGetter();

    NitDescGetter nide = new NitDescGetter();

    EitDescGetter eide = new EitDescGetter();

    for (Section s : sections) {
        sde.process(s);
        nide.process(s);
        eide.process(s);
    }

    Set<Descriptor> descs = new HashSet<>();
    descs.addAll(sde.getUnmodifiableDest());
    descs.addAll(nide.getUnmodifiableDest());
    descs.addAll(eide.getUnmodifiableDest());

    Set<Integer> dtags = new TreeSet<>();
    for (Descriptor d : descs) {
        dtags.add(d.getDescriptor_tag());
    }

    for (Integer i : dtags) {
        LOG.info(Integer.toHexString(i));
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.ConsoleLicenseGenerator.java

protected Properties readPropertiesFile(String fileName) throws Exception {
    File file = new File(fileName);

    if (!file.exists())
        throw new FileNotFoundException("The file [" + fileName + "] does not exist.");
    if (!file.canRead())
        throw new IOException("The file [" + fileName + "] is not readable.");

    InputStreamReader reader = null;
    FileInputStream stream = null;
    try {//from  ww  w  . ja va  2s  . c  o m
        stream = new FileInputStream(file);
        reader = new InputStreamReader(stream, LicensingCharsets.UTF_8);

        Properties properties = new Properties();
        properties.load(reader);

        return properties;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Throwable ignore) {
            }
        }

        if (stream != null) {
            try {
                stream.close();
            } catch (Throwable ignore) {
            }
        }
    }
}

From source file:de.hybris.platform.test.LocalizationFilesTest.java

/**
 * Checks if the file was formatted correctly in UTF-8.
 *//*from   ww  w . j av a 2s  .c  o m*/
@Test
public void testEncodedInUTF8() {
    boolean successfulTest = true;
    final List<String> failMessages = new LinkedList<String>();

    for (final File file : allLocalizationFiles) {
        try {
            final FileInputStream fileStream = new FileInputStream(file);
            final InputStreamReader inputStream = new InputStreamReader(fileStream);
            final BufferedReader reader = new BufferedReader(inputStream);
            final byte[] bytes = new byte[1000000];

            fileStream.read(bytes);
            if (!isValidUTF8(bytes)) {
                final String message = "The file does not have the correct encoding: "
                        + file.getAbsolutePath().substring(prePathLength);
                LOG.error(message);
                failMessages.add(message);
                successfulTest = false;
            }

            reader.close();
            inputStream.close();
            fileStream.close();
        } catch (final FileNotFoundException fnFE) {
            final String message = "The file was removed while testing: "
                    + file.getAbsolutePath().substring(prePathLength);
            LOG.error(message);
            failMessages.add(message);
            successfulTest = false;
        } catch (final IOException e) {
            final String message = "There was an error while reading the file: "
                    + file.getAbsolutePath().substring(prePathLength);
            LOG.error(message);
            failMessages.add(message);
            successfulTest = false;
        }
    }
    final StringBuilder failedMessage = new StringBuilder();
    for (final String message : failMessages) {
        failedMessage.append(message + "\n");
    }
    failedMessage.append(failMessages.size() + " Files in total.");
    assertTrue(failedMessage.toString(), successfulTest);
}

From source file:com.android.yijiang.kzx.http.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity returned HttpEntity/*from w  w  w . j  a v a 2  s  .  c o m*/
 * @return deconstructed response
 * @throws java.io.IOException
 * @see org.apache.http.HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                        /*ignore*/ }
                }
            }
        }
    }
    return null;
}

From source file:com.fujitsu.dc.client.http.DcResponse.java

/**
 * This method is used to the response body in string format.
 * @param enc Character code// ww  w.j a  v a  2s  .  co m
 * @return Body text
 * @throws DaoException Exception thrown
 */
public final String bodyAsString(final String enc) throws DaoException {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader reader = null;
    try {
        is = this.getResponseBodyInputStream(response);
        if (is == null) {
            return "";
        }
        isr = new InputStreamReader(is, enc);
        reader = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        int chr;
        while ((chr = reader.read()) != -1) {
            sb.append((char) chr);
        }
        return sb.toString();
    } catch (IOException e) {
        throw DaoException.create("io exception", 0);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            throw DaoException.create("io exception", 0);
        } finally {
            try {
                if (isr != null) {
                    isr.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e2) {
                throw DaoException.create("io exception", 0);
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (Exception e3) {
                    throw DaoException.create("io exception", 0);
                }
            }
        }
    }
}