Example usage for java.io FileReader read

List of usage examples for java.io FileReader read

Introduction

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

Prototype

public int read(char cbuf[], int offset, int length) throws IOException 

Source Link

Document

Reads characters into a portion of an array.

Usage

From source file:edu.ur.ir.index.DefaultPlainTextExtractor.java

/**
 * Extract text from the plain text document
 * @throws Exception /*w  ww .jav  a2 s . c  o  m*/
 * 
 * @see edu.ur.ir.index.FileTextExtractor#getText(java.io.File)
 */
public String getText(File f) throws Exception {
    String text = null;
    // don't even try if the file is too large
    if (isFileTooLarge(f)) {
        return text;
    }
    FileReader reader = null;
    StringBuffer sb = new StringBuffer();
    char[] buffer = new char[1024];

    if (f.exists() && f.isFile() && (f.length() > 0)) {
        try {
            reader = new FileReader(f);
            int count = 0;

            while (count != -1) {
                count = reader.read(buffer, 0, bufferSize);
                // write out those same bytes
                if (count > 0) {
                    sb.append(buffer, 0, count);
                }
            }

            if (sb != null && !sb.toString().trim().equals("")) {
                text = sb.toString();
            }
        } catch (OutOfMemoryError oome) {
            text = null;
            log.error("could not extract text", oome);
            throw (oome);
        } catch (Exception e) {
            text = null;
            log.error("could not create document", e);
            throw (e);
        }

        finally {
            if (reader != null) {
                try {
                    reader.close();
                    reader = null;
                } catch (Exception e) {
                    log.error("could not close reader", e);
                    reader = null;
                }
            }
        }

    }

    return text;
}

From source file:org.apache.axis.handlers.JWSHandler.java

/**
 * If our path ends in the right file extension (*.jws), handle all the
 * work necessary to compile the source file if it needs it, and set
 * up the "proxy" RPC service surrounding it as the MessageContext's
 * active service./*from w  w  w .java  2 s  . co m*/
 *
 */
protected void setupService(MessageContext msgContext) throws Exception {
    // FORCE the targetService to be JWS if the URL is right.
    String realpath = msgContext.getStrProp(Constants.MC_REALPATH);
    String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION);
    if (extension == null)
        extension = DEFAULT_JWS_FILE_EXTENSION;

    if ((realpath != null) && (realpath.endsWith(extension))) {
        /* Grab the *.jws filename from the context - should have been */
        /* placed there by another handler (ie. HTTPActionHandler)     */
        /***************************************************************/
        String jwsFile = realpath;
        String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH);

        // Check for file existance, report error with
        // relative path to avoid giving out directory info.
        File f2 = new File(jwsFile);
        if (!f2.exists()) {
            throw new FileNotFoundException(rel);
        }

        if (rel.charAt(0) == '/') {
            rel = rel.substring(1);
        }

        int lastSlash = rel.lastIndexOf('/');
        String dir = null;

        if (lastSlash > 0) {
            dir = rel.substring(0, lastSlash);
        }

        String file = rel.substring(lastSlash + 1);

        String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR);
        if (outdir == null)
            outdir = ".";

        // Build matching directory structure under the output
        // directory.  In other words, if we have:
        //    /webroot/jws1/Foo.jws
        //
        // That will be compiled to:
        //    .../jwsOutputDirectory/jws1/Foo.class
        if (dir != null) {
            outdir = outdir + File.separator + dir;
        }

        // Confirm output directory exists.  If not, create it IF we're
        // allowed to.
        // !!! TODO: add a switch to control this.
        File outDirectory = new File(outdir);
        if (!outDirectory.exists()) {
            outDirectory.mkdirs();
        }

        if (log.isDebugEnabled())
            log.debug("jwsFile: " + jwsFile);

        String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1)
                + "java";
        String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1)
                + "class";

        if (log.isDebugEnabled()) {
            log.debug("jFile: " + jFile);
            log.debug("cFile: " + cFile);
            log.debug("outdir: " + outdir);
        }

        File f1 = new File(cFile);

        /* Get the class */
        /*****************/
        String clsName = null;
        //clsName = msgContext.getStrProp(Constants.MC_RELATIVE_PATH);
        if (clsName == null)
            clsName = f2.getName();
        if (clsName != null && clsName.charAt(0) == '/')
            clsName = clsName.substring(1);

        clsName = clsName.substring(0, clsName.length() - extension.length());
        clsName = clsName.replace('/', '.');

        if (log.isDebugEnabled())
            log.debug("ClsName: " + clsName);

        /* Check to see if we need to recompile */
        /****************************************/
        if (!f1.exists() || f2.lastModified() > f1.lastModified()) {
            /* If the class file doesn't exist, or it's older than the */
            /* java file then recompile the java file.                 */
            /* Start by copying the *.jws file to *.java               */
            /***********************************************************/
            log.debug(Messages.getMessage("compiling00", jwsFile));
            log.debug(Messages.getMessage("copy00", jwsFile, jFile));
            FileReader fr = new FileReader(jwsFile);
            FileWriter fw = new FileWriter(jFile);
            char[] buf = new char[4096];
            int rc;
            while ((rc = fr.read(buf, 0, 4095)) >= 0)
                fw.write(buf, 0, rc);
            fw.close();
            fr.close();

            /* Now run javac on the *.java file */
            /************************************/
            log.debug("javac " + jFile);
            // Process proc = rt.exec( "javac " + jFile );
            // proc.waitFor();
            Compiler compiler = CompilerFactory.getCompiler();

            compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext));
            compiler.setDestination(outdir);
            compiler.addFile(jFile);

            boolean result = compiler.compile();

            /* Delete the temporary *.java file and check return code */
            /**********************************************************/
            (new File(jFile)).delete();

            if (!result) {
                /* Delete the *class file - sometimes it gets created even */
                /* when there are errors - so erase it so it doesn't       */
                /* confuse us.                                             */
                /***********************************************************/
                (new File(cFile)).delete();

                Document doc = XMLUtils.newDocument();

                Element root = doc.createElementNS("", "Errors");
                StringBuffer message = new StringBuffer("Error compiling ");
                message.append(jFile);
                message.append(":\n");

                List errors = compiler.getErrors();
                int count = errors.size();
                for (int i = 0; i < count; i++) {
                    CompilerError error = (CompilerError) errors.get(i);
                    if (i > 0)
                        message.append("\n");
                    message.append("Line ");
                    message.append(error.getStartLine());
                    message.append(", column ");
                    message.append(error.getStartColumn());
                    message.append(": ");
                    message.append(error.getMessage());
                }
                root.appendChild(doc.createTextNode(message.toString()));
                throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null,
                        new Element[] { root });
            }
            ClassUtils.removeClassLoader(clsName);
            // And clean out the cached service.
            soapServices.remove(clsName);
        }

        ClassLoader cl = ClassUtils.getClassLoader(clsName);
        if (cl == null) {
            cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile);
        }

        msgContext.setClassLoader(cl);

        /* Create a new RPCProvider - this will be the "service"   */
        /* that we invoke.                                                */
        /******************************************************************/
        // Cache the rpc service created to handle the class.  The cache
        // is based on class name, so only one .jws/.jwr class can be active
        // in the system at a time.
        SOAPService rpc = (SOAPService) soapServices.get(clsName);
        if (rpc == null) {
            rpc = new SOAPService(new RPCProvider());
            rpc.setName(clsName);
            rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName);
            rpc.setEngine(msgContext.getAxisEngine());

            // Support specification of "allowedMethods" as a parameter.
            String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS);
            if (allowed == null)
                allowed = "*";
            rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed);
            // Take the setting for the scope option from the handler
            // parameter named "scope"
            String scope = (String) getOption(RPCProvider.OPTION_SCOPE);
            if (scope == null)
                scope = Scope.DEFAULT.getName();
            rpc.setOption(RPCProvider.OPTION_SCOPE, scope);

            rpc.getInitializedServiceDesc(msgContext);

            soapServices.put(clsName, rpc);
        }

        // Set engine, which hooks up type mappings.
        rpc.setEngine(msgContext.getAxisEngine());

        rpc.init(); // ??

        // OK, this is now the destination service!
        msgContext.setService(rpc);
    }

    if (log.isDebugEnabled()) {
        log.debug("Exit: JWSHandler::invoke");
    }
}

From source file:edu.ku.brc.specify.toycode.mexconabio.FileMakerToMySQL.java

/**
 * @param fileName//from w  ww .  ja v  a  2s. c om
 */
protected void cleanFile(final String fileName) {
    File srcFile = new File(fileName);
    try {
        File destFile = new File("xxx.xml");//File.createTempFile("DB", "xml");
        FileUtils.copyFile(srcFile, destFile);

        //System.out.println("Clean FIle: "+dest)

        FileReader fr = new FileReader(srcFile);
        PrintWriter pw = new PrintWriter(destFile);
        char[] chars = new char[4096 * 8];
        int numChars = fr.read(chars, 0, chars.length);
        while (numChars > 0) {
            for (int i = 0; i < chars.length; i++) {
                //if (chars[i] < 32 || chars[i] > 126)
                if (chars[i] == 0xb) {
                    System.out.println("fixed[" + chars[i] + "]");
                    chars[i] = ' ';

                }
            }
            pw.write(chars, 0, numChars);
            numChars = fr.read(chars, 0, chars.length);
        }

        fr.close();
        pw.close();

        FileUtils.copyFile(destFile, srcFile);

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.clustercontrol.util.KeyCheck.java

/**
 * /*  ww  w . j  a  v a  2s . c  om*/
 * @param type
 * @return
 */
private static boolean checkCommon(String type) {

    boolean keyCheck = false;

    String etcdir = System.getProperty("hinemos.manager.etc.dir");

    File[] files = null;
    PublicKey publicKey = null;
    try {
        publicKey = getPublicKey(PUBLIC_KEY_STR);
        m_log.info("etcdir=" + etcdir);
        File directory = new File(etcdir); // TODO ?????
        files = directory.listFiles();
        if (files == null) {
            m_log.warn(etcdir + " does not exist");
            return false;
        }
        m_log.info("key files=" + files.length);
    } catch (Exception e) {
        m_log.warn(e.getMessage(), e);
        return false;
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
    int yearMonth = Integer.parseInt(sdf.format(new Date()));
    for (File file : files) {
        FileReader fileReader = null;
        try {
            String filename = file.getName();
            String filenamePre = filename.substring(0, 6);

            /*
             * ?0:
             * ??????
             * ??????
             */
            String[] fileTypeArr = filename.split("_");
            if (fileTypeArr.length != 3 || !fileTypeArr[2].equals(type)) {
                m_log.debug("file type different. fileName:" + filename + ", targetType:" + type);
                continue;
            }

            /*
             * ?1:
             * ???
             * ???prefix???????
             * ????????201401_001???????prefix=201401
             */
            m_log.trace("filename=" + filename + ", filePrefix=" + filenamePre);
            if (yearMonth <= Integer.parseInt(filenamePre)) {
                m_log.debug("OK time limit, filename=" + filename);
            } else {
                m_log.debug("NG time limit, filename=" + filename);
                continue;
            }

            /*
             * ?2:
             * ?????????????????
             */
            fileReader = new FileReader(file);
            int charLength = 256;
            char[] cbuf = new char[charLength];
            fileReader.read(cbuf, 0, charLength);
            String str = decrypt(new String(cbuf), publicKey);
            m_log.trace("filename=" + filename + ", contents=" + str);
            if (filename.equals(str)) {
                m_log.debug("OK valid file, filename=" + filename);
                // ????????????
                keyCheck = true;
                break;
            } else {
                m_log.debug("NG valid file, filename=" + filename);
                continue;
            }
        } catch (Exception e) {
            if (e instanceof NumberFormatException) {
                m_log.info(e.getMessage());
            } else {
                m_log.info(e.getMessage(), e);
            }
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    // nop
                }
            }
        }
    }
    m_log.info("license check result:" + keyCheck);
    return keyCheck;
}

From source file:org.regenstrief.util.Util.java

/**
 * Reads the file with the given name//from  w w w . j a  v  a2 s  .  co m
 * 
 * @param name the file name
 * @return the contents of the file
 * @throws IOException if an I/O error occurs while reading the file
 **/
public final static String readFile(final String name) throws IOException {
    System.out.println(" errrrr ");
    final StringBuilder sb = new StringBuilder();
    final char[] buffer = new char[BUFFER_SIZE];
    FileReader f = null;
    int i = 0;
    InputStream is;

    try {
        f = new FileReader(name);
        while (i >= 0) {
            i = f.read(buffer, 0, BUFFER_SIZE);
            if (i > 0) {
                sb.append(buffer, 0, i);
            }
        }

        f.close();
        return sb.toString();
    } catch (final Exception e) {
    }
    is = getStreamRequired(name);
    try {
        return readStream(is);
    } finally {
        is.close();
    }
}