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:org.dbflute.task.bs.DfAbstractTexenTask.java

protected static String fileContentsToString(String filePath) {
    String contents = "";
    final File file = new File(filePath);
    if (file.exists()) {
        FileReader fr = null;
        try {//from www  . ja  v a2s.c  om
            fr = new FileReader(file);
            final char template[] = new char[(int) file.length()];
            fr.read(template);
            contents = new String(template);
        } catch (Exception e) {
            throw new IllegalStateException("Failed to read the file: " + filePath, e);
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
    return contents;
}

From source file:de.mpg.escidoc.services.test.search.TestBase.java

/**
 * Reads contents from text file and returns it as String.
 * //from ww  w  .  jav  a  2  s.co  m
 * @param fileName Name of input file
 * @return Entire contents of filename as a String
 * @throws FileNotFoundException
 */
public static String readFile(String fileName) {
    boolean isFileNameNull = (fileName == null);
    StringBuffer fileBuffer;
    String fileString = null;
    String line;
    if (!isFileNameNull) {
        try {
            File file = new File(fileName);
            FileReader in = new FileReader(file);
            BufferedReader dis = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            fileBuffer = new StringBuffer();
            while ((line = dis.readLine()) != null) {
                fileBuffer.append(line + "\n");
            }
            in.close();
            fileString = fileBuffer.toString();
        } catch (IOException e) {
            return null;
        }
    }
    return fileString;
}

From source file:net.rim.ejde.internal.util.PackageUtils.java

/**
 * Get package id for java file in com.rim.test format
 *
 * @param file//from w w  w .j  a v a 2 s .  co  m
 *            File
 * @return packageId String
 */
public static String getJavaFilePackageID(File file) {
    String packageId = EMPTY_STRING;
    if (file == null) {
        return EMPTY_STRING;
    }
    try {
        FileReader fileReader = new FileReader(file);
        JavaParser parser = new JavaParser(file, fileReader, true);
        packageId = parser.getPackage();
        try {
            fileReader.close();
        } catch (IOException ioe) {
            _logger.error(ioe);
        }
        return packageId; // com.rim.test
    } catch (FileNotFoundException fnfe) {
        return EMPTY_STRING;
    }
}

From source file:com.bhb27.isu.tools.Tools.java

public static String readFileN(String file, boolean asRoot) {

    StringBuilder s = null;/*from   www .  j av a2  s . c  o  m*/
    FileReader fileReader = null;
    BufferedReader buf = null;
    try {
        fileReader = new FileReader(file);
        buf = new BufferedReader(fileReader);

        String line;
        s = new StringBuilder();
        while ((line = buf.readLine()) != null)
            s.append(line).append("\n");
    } catch (FileNotFoundException ignored) {
        Log.e(TAG, "File does not exist " + file);
    } catch (IOException e) {
        Log.e(TAG, "Failed to read " + file);
    } finally {
        try {
            if (fileReader != null)
                fileReader.close();
            if (buf != null)
                buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return s == null ? null : s.toString().trim();
}

From source file:com.bhb27.isu.tools.Tools.java

public static String readFile(String file, boolean asRoot) {
    if (asRoot) {
        if (SuBinary(xbin_su))
            return new RootFile(file).readFile();
        else if (SuBinary(xbin_isu))
            return new RootFile(file).IreadFile();
    }/* w  ww .j  a  v a  2s.  com*/

    StringBuilder s = null;
    FileReader fileReader = null;
    BufferedReader buf = null;
    try {
        fileReader = new FileReader(file);
        buf = new BufferedReader(fileReader);

        String line;
        s = new StringBuilder();
        while ((line = buf.readLine()) != null)
            s.append(line).append("\n");
    } catch (FileNotFoundException ignored) {
        Log.e(TAG, "File does not exist " + file);
    } catch (IOException e) {
        Log.e(TAG, "Failed to read " + file);
    } finally {
        try {
            if (fileReader != null)
                fileReader.close();
            if (buf != null)
                buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return s == null ? null : s.toString().trim();
}

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

/**
 * Import documents from filesystem into document repository (recursive).
 *///from   w ww . ja va 2  s  .c o  m
private static ImpExpStats importDocumentsHelper(String token, File fs, String fldPath, String 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 });
    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) && !fileName.endsWith(".xml")) {
            if (files[i].isDirectory()) {
                Folder fld = new Folder();
                boolean api = false;
                int importedFolder = 0;
                log.info("Directory: {}", files[i]);

                try {
                    if (metadata.equals("JSON")) {
                        // 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 if (metadata.equals("XML")) {
                        // Read serialized folder metadata
                        File jsFile = new File(files[i].getPath() + ".xml");
                        log.info("Folder Metadata: {}", jsFile.getPath());

                        if (jsFile.exists() && jsFile.canRead()) {
                            FileReader fr = new FileReader(jsFile);
                            JAXBContext jaxbContext = JAXBContext.newInstance(FolderMetadata.class);

                            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                            FolderMetadata fmd = (FolderMetadata) jaxbUnmarshaller.unmarshal(fr);
                            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());
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                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")) {
                    log.info("Mail: {}", files[i]);
                    ImpExpStats tmp = importMail(token, fs, 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.debug("importDocumentsHelper: {}", stats);
    return stats;
}

From source file:org.alfresco.bm.cmis.AbstractCMISEventProcessor.java

/**
 * Static helper to find and extract a search term from the given file
 * /*from   w w w . j  a  v a 2 s  . c  om*/
 * @param testFileService           the test files
 * @param searchTermsFilename       the name of the file to find
 * @return                          a list of search terms (empty if there are none or the remote file does not exist)
 */
public static String[] getSearchStrings(TestFileService testFileService, String searchTermsFilename) {
    File file = testFileService.getFileByName(searchTermsFilename);
    if (file == null) {
        return new String[0];
    }
    FileReader fr = null;
    try {
        fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        ArrayList<String> strings = new ArrayList<String>(500);
        String line;
        while ((line = br.readLine()) != null) {
            strings.add(line);
        }
        // Check
        if (strings.size() == 0) {
            throw new RuntimeException("No search strings in file: " + searchTermsFilename);
        }
        // Push into an array
        return (String[]) strings.toArray(new String[strings.size()]);
    } catch (IOException e) {
        throw new RuntimeException(
                "Failed to read search strings from file '" + file + "' loaded as '" + searchTermsFilename);
    } finally {
        if (fr != null) {
            try {
                fr.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:nl.nn.adapterframework.util.Misc.java

/**
  * Please consider using resourceToString() instead of relying on files.
 *//*from   w w w. j ava2 s  . c o m*/
public static String fileToString(String fileName, String endOfLineString, boolean xmlEncode)
        throws IOException {
    FileReader reader = new FileReader(fileName);
    try {
        return readerToString(reader, endOfLineString, xmlEncode);
    } finally {
        reader.close();
    }
}

From source file:org.haplo.javascript.Runtime.java

/**
 * Initialize the shared JavaScript environment. Loads libraries and removes
 * methods of escaping the sandbox./* w  w w .ja v  a2 s .c  o  m*/
 */
public static void initializeSharedEnvironment(String frameworkRoot, boolean pluginDebuggingEnabled)
        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);
        // Define the HaploTemplate host object now, so the JS code can use it to parse templates
        // TODO: Convert all standard templates from Handlebars, move HaploTemplate host object declaraction back with the others, remove $HaploTemplate from whitelist
        defineSealedHostClass(scope, HaploTemplate.class);

        // 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();

        // Insert plugin debugging flag
        if (pluginDebuggingEnabled) {
            Scriptable o = (Scriptable) scope.get("O", scope);
            o.put("PLUGIN_DEBUGGING_ENABLED", o, true);
        }

        // 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, KHost.class);
        defineSealedHostClass(scope, KPlatformGenericInterface.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, KBinaryDataInMemory.class, true /* map inheritance */);
        defineSealedHostClass(scope, KBinaryDataStaticFile.class, true /* map inheritance */);
        defineSealedHostClass(scope, KBinaryDataTempFile.class, true /* map inheritance */);
        defineSealedHostClass(scope, KUploadedFile.class, true /* map inheritance */);
        defineSealedHostClass(scope, KStoredFile.class);
        defineSealedHostClass(scope, KJob.class);
        defineSealedHostClass(scope, KFilePipelineResult.class);
        defineSealedHostClass(scope, KSessionStore.class);
        defineSealedHostClass(scope, KKeychainCredential.class);

        // HaploTemplate created earlier as required by some of the setup
        defineSealedHostClass(scope, HaploTemplateDeferredRender.class);
        defineSealedHostClass(scope, JSFunctionThis.class);
        defineSealedHostClass(scope, GenericDeferredRender.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, JdDynamicTable.class, true /* map inheritance */);
        defineSealedHostClass(scope, JdSelectClause.class);
        defineSealedHostClass(scope, JdSelect.class, true /* map inheritance */);

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

        defineSealedHostClass(scope, KRefKeyDictionary.class);
        defineSealedHostClass(scope, KRefKeyDictionaryHierarchical.class, true /* map inheritance */);
        defineSealedHostClass(scope, KRefSet.class);
        defineSealedHostClass(scope, KCheckingLookupObject.class);
        defineSealedHostClass(scope, WorkUnitTags.class);
        defineSealedHostClass(scope, GetterDictionaryBase.class);
        defineSealedHostClass(scope, InterRuntimeSignal.class);
        defineSealedHostClass(scope, KRequestContinuation.class);
        defineSealedHostClass(scope, JsBigDecimal.class);
        defineSealedHostClass(scope, JsDecimalFormat.class);

        defineSealedHostClass(scope, XmlDocument.class);
        defineSealedHostClass(scope, XmlCursor.class);

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

        defineSealedHostClass(scope, KAuthenticationService.class);

        defineSealedHostClass(scope, KMessageBusPlatformSupport.class);
        defineSealedHostClass(scope, KUUIDPlatformSupport.class);

        defineSealedHostClass(scope, StdReporting.class);
        defineSealedHostClass(scope, StdWebPublisher.class);
        defineSealedHostClass(scope, StdWebPublisher.RenderedAttributeListView.class);
        defineSealedHostClass(scope, StdWebPublisher.ValueView.class);

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

        // Check JavaScript TimeZone
        checkJavaScriptTimeZoneIsGMT();

        // Templating integration
        JSPlatformIntegration.parserConfiguration = new TemplateParserConfiguration();
        JSPlatformIntegration.includedTemplateRenderer = new TemplateIncludedRenderer();
        JSPlatformIntegration.platformFunctionRenderer = new TemplateFunctionRenderer();

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

    initializeSharedEnvironmentTimeTaken = System.currentTimeMillis() - startTime;
}

From source file:LoadSync.java

public static void doLoadCommand(JTextComponent textComponent, String filename) {
    FileReader reader = null;
    try {/*from   www . ja v a2s .  c om*/
        System.out.println("Loading");
        reader = new FileReader(filename);

        // Create empty HTMLDocument to read into
        HTMLEditorKit htmlKit = new HTMLEditorKit();
        HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
        // Create parser (javax.swing.text.html.parser.ParserDelegator)
        HTMLEditorKit.Parser parser = new ParserDelegator();
        // Get parser callback from document
        HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
        // Load it (true means to ignore character set)
        parser.parse(reader, callback, true);
        // Replace document
        textComponent.setDocument(htmlDoc);
        System.out.println("Loaded");

    } catch (IOException exception) {
        System.out.println("Load oops");
        exception.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignoredException) {
            }
        }
    }
}