Example usage for java.io FileReader close

List of usage examples for java.io FileReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:Main.java

/**
 * Reads data from specified file.//from   w  ww .java2s.  co m
 * @param file A file to read from.
 * @return 2-dimensional array of data.
 */
public static ArrayList<ArrayList<String>> loadFile(File file) {
    FileReader fr = null;
    String line = "";
    ArrayList<ArrayList<String>> dataArray = new ArrayList<>();

    try {
        fr = new FileReader(file);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        System.out.println(e.getMessage());
    }

    BufferedReader br = new BufferedReader(fr);
    ArrayList<String> tokens = new ArrayList<>();

    try {
        while ((line = br.readLine()) != null) {
            tokens = parseLine(line);
            dataArray.add(tokens);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        fr.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return dataArray;
}

From source file:com.alibaba.rocketmq.common.MixAll.java

public static final String file2String(final String fileName) {
    File file = new File(fileName);
    if (file.exists()) {
        char[] data = new char[(int) file.length()];
        boolean result = false;

        FileReader fileReader = null;
        try {//from w w w.j a  v a  2 s  .co m
            fileReader = new FileReader(file);
            int len = fileReader.read(data);
            result = (len == data.length);
        } catch (IOException e) {
            // e.printStackTrace();
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (result) {
            String value = new String(data);
            return value;
        }
    }
    return null;
}

From source file:org.eclipse.virgo.ide.manifest.core.BundleManifestUtils.java

/**
 * Dumps a new MANIFEST.MF into the given {@link IJavaProject}.
 *///from  w w w . j  av  a2  s. c  o m
public static void createNewBundleManifest(IJavaProject javaProject, String symbolicName, String bundleVersion,
        String providerName, String bundleName, String serverModule, Map<String, String> properties) {

    BundleManifest manifest = null;

    File existingManifestFile = locateManifestFile(javaProject, false);
    if (existingManifestFile != null) {
        FileReader reader = null;
        try {
            reader = new FileReader(existingManifestFile);
            manifest = BundleManifestFactory.createBundleManifest(new FileReader(existingManifestFile));
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        manifest = BundleManifestFactory.createBundleManifest();
    }

    manifest.setBundleManifestVersion(2);
    Dictionary<String, String> dictonary = manifest.toDictionary();
    if (StringUtils.isNotBlank(symbolicName)) {
        dictonary.put(Constants.BUNDLE_SYMBOLICNAME, symbolicName);
    }
    if (StringUtils.isNotBlank(bundleVersion)) {
        dictonary.put(Constants.BUNDLE_VERSION, bundleVersion);
    }
    if (StringUtils.isNotBlank(bundleName)) {
        dictonary.put(Constants.BUNDLE_NAME, bundleName);
    }
    if (StringUtils.isNotBlank(providerName)) {
        dictonary.put(Constants.BUNDLE_DESCRIPTION, providerName);
    }

    for (Map.Entry<String, String> entry : properties.entrySet()) {
        if (StringUtils.isNotEmpty(entry.getValue()) && StringUtils.isNotEmpty(entry.getKey())) {
            dictonary.put(entry.getKey(), entry.getValue());
        }
    }

    Writer writer = null;
    try {
        if (existingManifestFile != null) {
            writer = new FileWriter(existingManifestFile);
        } else {
            writer = new FileWriter(
                    getFirstPossibleManifestFile(javaProject.getProject(), false).getRawLocation().toFile());
        }
        BundleManifest bundleManifest = BundleManifestFactory.createBundleManifest(dictonary);
        bundleManifest.write(writer);
    } catch (IOException e) {
    } finally {
        if (writer != null) {
            try {
                writer.flush();
                writer.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:fileoperations.FileOperations.java

public static Object readFromJSONFile(String fileToReadFrom) {
    loggerObj.log(Level.INFO, "Inside readFromJSONFile method");
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;

    try {//from  w  ww. j av  a 2s . c  o  m
        loggerObj.log(Level.INFO, "file to read from is:" + fileToReadFrom);
        fileReader = new FileReader(fileToReadFrom);
        Object obj = parser.parse(fileReader);
        loggerObj.log(Level.INFO, "JSON Object is validated successfully from" + fileToReadFrom);
        fileReader.close();
        return obj;
    } catch (IOException ex) {
        try {
            loggerObj.log(Level.SEVERE, "Error in reading the JSON from the file " + fileToReadFrom
                    + "\n Exception is: " + ex.toString());
            if (fileReader != null) {
                fileReader.close();
            }

        } catch (IOException ex1) {
            loggerObj.log(Level.SEVERE,
                    "Error in closing the file after problem in reading the JSON from the file "
                            + fileToReadFrom);
        }
        return null;
    } catch (ParseException ex) {
        try {
            loggerObj.log(Level.SEVERE, "Error in validating  the JSON from the file" + fileToReadFrom
                    + "Exception " + ex.toString());
            if (fileReader != null) {
                fileReader.close();
            }
        } catch (IOException ex1) {
            loggerObj.log(Level.SEVERE,
                    "Error in closing the file after problem in parsing the JSON from the file "
                            + fileToReadFrom);
        }

        return null;

    }

}

From source file:es.csic.iiia.planes.cli.Cli.java

/**
 * Parse the provided list of arguments according to the program's options.
 * //from w  ww .  ja v a2 s  .  c om
 * @param in_args
 *            list of input arguments.
 * @return a configuration object set according to the input options.
 */
private static Configuration parseOptions(String[] in_args) {
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    Properties settings = loadDefaultSettings();

    try {
        line = parser.parse(options, in_args);
    } catch (ParseException ex) {
        Logger.getLogger(Cli.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        showHelp();
    }

    if (line.hasOption('h')) {
        showHelp();
    }

    if (line.hasOption('d')) {
        dumpSettings();
    }

    if (line.hasOption('s')) {
        String fname = line.getOptionValue('s');
        try {
            settings.load(new FileReader(fname));
        } catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load the settings file \"" + fname + "\"");
        }
    }

    // Apply overrides
    settings.setProperty("gui", String.valueOf(line.hasOption('g')));
    settings.setProperty("quiet", String.valueOf(line.hasOption('q')));
    Properties overrides = line.getOptionProperties("o");
    settings.putAll(overrides);

    String[] args = line.getArgs();
    if (args.length < 1) {
        showHelp();
    }
    settings.setProperty("problem", args[0]);

    Configuration c = new Configuration(settings);
    System.out.println(c.toString());
    /**
     * Modified by Guillermo B. Print settings to a result file, titled
     * "results.txt"
     */
    try {
        FileWriter fw = new FileWriter("results.txt", true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw);
        String[] results = c.toString().split("\n");
        // out.println(results[8]);

        for (String s : results) {
            out.println(s);

        }
        // out.println(results[2]);
        // out.println(results[8]);
        out.close();
    } catch (IOException e) {
    }

    /**
     * Modified by Ebtesam Save settings to a .csv file, titled
     * "resultsCSV.csv"
     */

    try {
        FileWriter writer = new FileWriter("resultsCSV.csv", true);
        FileReader reader = new FileReader("resultsCSV.csv");

        String header = "SAR Strategy,# of Searcher UAVs,# of Survivors,"
                + "# of Survivors rescued,Min.Time needed to rescue Survivors,Mean. Time needed to rescue Survivors,Max. Time needed to rescue Survivors,"
                + "# of Survivors found,Min. Time needed to find Survivors,Mean Time needed to find Survivors,Max. Time needed to find Survivors,"
                + "Running Time of Simulation\n";
        if (reader.read() == -1) {
            writer.append(header);
            writer.append("\n");
        }
        reader.close();
        String[] results = c.toString().split("\n");
        writer.append(results[2].substring(10));
        writer.append(",");
        writer.append(results[20].substring(11));
        writer.append(",");
        writer.append(results[30].substring(18));
        writer.write(",");
        writer.close();
    } catch (IOException e) {
    }

    if (line.hasOption('t')) {
        System.exit(0);
    }
    return c;
}

From source file:com.oneis.javascript.Runtime.java

/**
 * Initialize the shared JavaScript environment. Loads libraries and removes
 * methods of escaping the sandbox.// www . java2s.  com
 */
public static void initializeSharedEnvironment(String frameworkRoot) throws java.io.IOException {
    // Don't allow this to be called twice
    if (sharedScope != null) {
        return;
    }

    long startTime = System.currentTimeMillis();

    final Context cx = Runtime.enterContext();
    try {
        final ScriptableObject scope = cx.initStandardObjects(null,
                false /* don't seal the standard objects yet */);

        if (!scope.has("JSON", scope)) {
            throw new RuntimeException(
                    "Expecting built-in JSON support in Rhino, check version is at least 1.7R3");
        }

        if (standardTemplateLoader == null) {
            throw new RuntimeException("StandardTemplateLoader for Runtime hasn't been set.");
        }
        String standardTemplateJSON = standardTemplateLoader.standardTemplateJSON();
        scope.put("$STANDARDTEMPLATES", scope, standardTemplateJSON);

        // Load the library code
        FileReader bootScriptsFile = new FileReader(frameworkRoot + "/lib/javascript/bootscripts.txt");
        LineNumberReader bootScripts = new LineNumberReader(bootScriptsFile);
        String scriptFilename = null;
        while ((scriptFilename = bootScripts.readLine()) != null) {
            FileReader script = new FileReader(frameworkRoot + "/" + scriptFilename);
            cx.evaluateReader(scope, script, scriptFilename, 1, null /* no security domain */);
            script.close();
        }
        bootScriptsFile.close();

        // Load the list of allowed globals
        FileReader globalsWhitelistFile = new FileReader(
                frameworkRoot + "/lib/javascript/globalswhitelist.txt");
        HashSet<String> globalsWhitelist = new HashSet<String>();
        LineNumberReader whitelist = new LineNumberReader(globalsWhitelistFile);
        String globalName = null;
        while ((globalName = whitelist.readLine()) != null) {
            String g = globalName.trim();
            if (g.length() > 0) {
                globalsWhitelist.add(g);
            }
        }
        globalsWhitelistFile.close();

        // Remove all the globals which aren't allowed, using a whitelist            
        for (Object propertyName : scope.getAllIds()) // the form which includes the DONTENUM hidden properties
        {
            if (propertyName instanceof String) // ConsString is checked
            {
                // Delete any property which isn't in the whitelist
                if (!(globalsWhitelist.contains(propertyName))) {
                    scope.delete((String) propertyName); // ConsString is checked
                }
            } else {
                // Not expecting any other type of property name in the global namespace
                throw new RuntimeException(
                        "Not expecting global JavaScript scope to contain a property which isn't a String");
            }
        }

        // Run through the globals again, just to check nothing escaped
        for (Object propertyName : scope.getAllIds()) {
            if (!(globalsWhitelist.contains(propertyName))) {
                throw new RuntimeException("JavaScript global was not destroyed: " + propertyName.toString());
            }
        }
        // Run through the whilelist, and make sure that everything in it exists
        for (String propertyName : globalsWhitelist) {
            if (!scope.has(propertyName, scope)) {
                // The whitelist should only contain non-host objects created by the JavaScript source files.
                throw new RuntimeException(
                        "JavaScript global specified in whitelist does not exist: " + propertyName);
            }
        }
        // And make sure java has gone, to check yet again that everything expected has been removed
        if (scope.get("java", scope) != Scriptable.NOT_FOUND) {
            throw new RuntimeException("JavaScript global 'java' escaped destruction");
        }

        // Seal the scope and everything within in, so nothing else can be added and nothing can be changed
        // Asking initStandardObjects() to seal the standard library doesn't actually work, as it will leave some bits
        // unsealed so that decodeURI.prototype.pants = 43; works, and can pass information between runtimes.
        // This recursive object sealer does actually work. It can't seal the main host object class, so that's
        // added to the scope next, with the (working) seal option set to true.
        HashSet<Object> sealedObjects = new HashSet<Object>();
        recursiveSealObjects(scope, scope, sealedObjects, false /* don't seal the root object yet */);
        if (sealedObjects.size() == 0) {
            throw new RuntimeException("Didn't seal any JavaScript globals");
        }

        // Add the host object classes. The sealed option works perfectly, so no need to use a special seal function.
        defineSealedHostClass(scope, KONEISHost.class);
        defineSealedHostClass(scope, KObjRef.class);
        defineSealedHostClass(scope, KScriptable.class);
        defineSealedHostClass(scope, KLabelList.class);
        defineSealedHostClass(scope, KLabelChanges.class);
        defineSealedHostClass(scope, KLabelStatements.class);
        defineSealedHostClass(scope, KDateTime.class);
        defineSealedHostClass(scope, KObject.class);
        defineSealedHostClass(scope, KText.class);
        defineSealedHostClass(scope, KQueryClause.class);
        defineSealedHostClass(scope, KQueryResults.class);
        defineSealedHostClass(scope, KPluginAppGlobalStore.class);
        defineSealedHostClass(scope, KPluginResponse.class);
        defineSealedHostClass(scope, KTemplatePartialAutoLoader.class);
        defineSealedHostClass(scope, KAuditEntry.class);
        defineSealedHostClass(scope, KAuditEntryQuery.class);
        defineSealedHostClass(scope, KUser.class);
        defineSealedHostClass(scope, KUserData.class);
        defineSealedHostClass(scope, KWorkUnit.class);
        defineSealedHostClass(scope, KWorkUnitQuery.class);
        defineSealedHostClass(scope, KEmailTemplate.class);
        defineSealedHostClass(scope, KBinaryData.class);
        defineSealedHostClass(scope, KUploadedFile.class);
        defineSealedHostClass(scope, KStoredFile.class);
        defineSealedHostClass(scope, KJob.class);
        defineSealedHostClass(scope, KSessionStore.class);

        defineSealedHostClass(scope, KSecurityRandom.class);
        defineSealedHostClass(scope, KSecurityBCrypt.class);
        defineSealedHostClass(scope, KSecurityDigest.class);
        defineSealedHostClass(scope, KSecurityHMAC.class);

        defineSealedHostClass(scope, JdNamespace.class);
        defineSealedHostClass(scope, JdTable.class);
        defineSealedHostClass(scope, JdSelectClause.class);
        defineSealedHostClass(scope, JdSelect.class, true /* map inheritance */);

        defineSealedHostClass(scope, KGenerateTable.class);
        defineSealedHostClass(scope, KGenerateXLS.class, true /* map inheritance */);

        defineSealedHostClass(scope, KRefKeyDictionary.class);
        defineSealedHostClass(scope, KRefKeyDictionaryHierarchical.class, true /* map inheritance */);
        defineSealedHostClass(scope, KCheckingLookupObject.class);

        defineSealedHostClass(scope, KCollaborationService.class);
        defineSealedHostClass(scope, KCollaborationFolder.class);
        defineSealedHostClass(scope, KCollaborationItemList.class);
        defineSealedHostClass(scope, KCollaborationItem.class);

        defineSealedHostClass(scope, KAuthenticationService.class);

        // Seal the root now everything has been added
        scope.sealObject();

        // Check JavaScript TimeZone
        checkJavaScriptTimeZoneIsGMT();

        sharedScope = scope;
    } finally {
        cx.exit();
    }

    initializeSharedEnvironmentTimeTaken = System.currentTimeMillis() - startTime;
}

From source file:Main.java

private static void readFile(String fileName) throws IOException {
    String line;// www .  j  ava 2 s .co  m
    FileReader fr = null;
    BufferedReader br = null;
    try {
        fr = new FileReader(fileName);
        br = new BufferedReader(fr);
        while ((line = br.readLine()) != null) {

            if (line.isEmpty() || line.startsWith("%"))
                continue;
            if (fileName.equals(INTENT_GET_EXTRAS_METHODS)) {
                intentExtrasMethods.add(line);
            } else if (fileName.equals(API_MISUSE_METHODS)) {
                APIMisuseMethods.add(line);
            } else if (fileName.equals(ANDROID_CLASSES)) {
                androidClassPrefixes.add(line);
            } else if (fileName.equals(API_SINK_METHODS)) {
                APISinkMethods.add(line);
            }
        }

    } finally {
        if (br != null)
            br.close();
        if (fr != null)
            fr.close();
    }
}

From source file:com.openkm.util.impexp.RepositoryImporter.java

/**
 * Import documents from filesystem into document repository (recursive).
 *//*w w  w .j  a  va2  s .co m*/
private static ImpExpStats importDocumentsHelper(String token, File fs, String fldPath, boolean metadata,
        boolean history, boolean uuid, Writer out, InfoDecorator deco)
        throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException,
        IOException, DatabaseException, ExtensionException, AutomationException {
    log.debug("importDocumentsHelper({}, {}, {}, {}, {}, {}, {}, {})",
            new Object[] { token, fs, fldPath, metadata, history, uuid, out, deco });
    long begin = System.currentTimeMillis();
    File[] files = fs.listFiles(new RepositoryImporter.NoVersionFilenameFilter());
    ImpExpStats stats = new ImpExpStats();
    FolderModule fm = ModuleManager.getFolderModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    ma.setRestoreUuid(uuid);
    Gson gson = new Gson();

    for (int i = 0; i < files.length; i++) {
        String fileName = files[i].getName();

        if (!fileName.endsWith(Config.EXPORT_METADATA_EXT)) {
            if (files[i].isDirectory()) {
                Folder fld = new Folder();
                boolean api = false;
                int importedFolder = 0;
                log.info("Directory: {}", files[i]);

                try {
                    if (metadata) {
                        // Read serialized folder metadata
                        File jsFile = new File(files[i].getPath() + Config.EXPORT_METADATA_EXT);
                        log.info("Folder Metadata: {}", jsFile.getPath());

                        if (jsFile.exists() && jsFile.canRead()) {
                            FileReader fr = new FileReader(jsFile);
                            FolderMetadata fmd = gson.fromJson(fr, FolderMetadata.class);
                            fr.close();

                            // Apply metadata
                            fld.setPath(fldPath + "/" + fileName);
                            fmd.setPath(fld.getPath());
                            ma.importWithMetadata(fmd);

                            if (out != null) {
                                out.write(deco.print(files[i].getPath(), files[i].length(), null));
                                out.flush();
                            }
                        } else {
                            log.warn("Unable to read metadata file: {}", jsFile.getPath());
                            api = true;
                        }
                    } else {
                        api = true;
                    }

                    if (api) {
                        fld.setPath(fldPath + "/" + fileName);
                        fm.create(token, fld);
                        FileLogger.info(BASE_NAME, "Created folder ''{0}''", fld.getPath());

                        if (out != null) {
                            out.write(deco.print(files[i].getPath(), files[i].length(), null));
                            out.flush();
                        }
                    }

                    importedFolder = 1;
                } catch (ItemExistsException e) {
                    log.warn("ItemExistsException: {}", e.getMessage());

                    if (out != null) {
                        out.write(deco.print(files[i].getPath(), files[i].length(), "ItemExists"));
                        out.flush();
                    }

                    stats.setOk(false);
                    FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", fld.getPath());
                } catch (JsonParseException e) {
                    log.warn("JsonParseException: {}", e.getMessage());

                    if (out != null) {
                        out.write(deco.print(files[i].getPath(), files[i].length(), "Json"));
                        out.flush();
                    }

                    stats.setOk(false);
                    FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", fld.getPath());
                }

                ImpExpStats tmp = importDocumentsHelper(token, files[i], fld.getPath(), metadata, history, uuid,
                        out, deco);

                // Stats
                stats.setOk(stats.isOk() && tmp.isOk());
                stats.setSize(stats.getSize() + tmp.getSize());
                stats.setMails(stats.getMails() + tmp.getMails());
                stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
                stats.setFolders(stats.getFolders() + tmp.getFolders() + importedFolder);
            } else {
                log.info("File: {}", files[i]);

                if (fileName.endsWith(".eml") || fileName.endsWith(".msg")) {
                    log.info("Mail: {}", files[i]);
                    ImpExpStats tmp = importMail(token, fldPath, fileName, files[i], metadata, out, deco);

                    // Stats
                    stats.setOk(stats.isOk() && tmp.isOk());
                    stats.setSize(stats.getSize() + tmp.getSize());
                    stats.setMails(stats.getMails() + tmp.getMails());
                } else {
                    log.info("Document: {}", files[i]);
                    ImpExpStats tmp = importDocument(token, fs, fldPath, fileName, files[i], metadata, history,
                            out, deco);

                    // Stats
                    stats.setOk(stats.isOk() && tmp.isOk());
                    stats.setSize(stats.getSize() + tmp.getSize());
                    stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
                }
            }
        }
    }

    log.trace("importDocumentsHelper.Time: {}", System.currentTimeMillis() - begin);
    log.debug("importDocumentsHelper: {}", stats);
    return stats;
}

From source file:gov.va.chir.tagline.dao.FileDao.java

public static String[] getContents(final File file) throws IOException {
    final List<String> lines = new ArrayList<String>();

    FileReader fileReader = null;

    try {/*  w w w  .  j  a v  a2 s.  com*/
        fileReader = new FileReader(file);

        BufferedReader br = null;

        try {
            br = new BufferedReader(fileReader);

            String line = null;

            while ((line = br.readLine()) != null) {
                lines.add(line);
            }

        } finally {
            if (br != null) {
                br.close();
            }
        }

    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
    }

    return lines.toArray(new String[lines.size()]);
}

From source file:jeplus.TRNSYSWinTools.java

/**
 * Copy a file from one location to another
 *
 * @param from The source file to be copied
 * @param to The target file to write/*from   w w  w .ja  va 2 s  .co  m*/
 * @return Successful or not
 */
public static boolean fileCopy(String from, String to) {
    boolean success = true;
    try {
        FileReader in = new FileReader(from);
        FileWriter out = new FileWriter(to);
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.close();
    } catch (Exception ee) {
        logger.error("Error copying " + from + " to " + to, ee);
        success = false;
    }
    return success;
}