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(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:com.npower.unicom.sync.SyncResultWriter.java

/**
 * Writer/*from ww w  .j  a  va  2  s . com*/
 * @throws IOException
 */
public void close() throws IOException {
    this.bodyWriter.close();

    File outputFile = null;

    // 
    String requestFilename = this.requestFile.getName();
    String reponseFilename = requestFilename.substring(0, requestFilename.length() - ".req".length()) + ".res";
    if (this.totalRecords == this.successRecords) {
        // 
        File outputDir = new File(this.responseDir, SUB_DIR_FOR_RIGHT);
        if (!outputDir.exists()) {
            log.info("create directory: " + outputDir.getAbsolutePath());
            outputDir.mkdirs();
        }
        outputFile = new File(outputDir, reponseFilename);
    } else if (this.totalRecords == this.errorRecords) {
        // 
        File outputDir = new File(this.responseDir, SUB_DIR_FOR_BAD);
        if (!outputDir.exists()) {
            log.info("create directory: " + outputDir.getAbsolutePath());
            outputDir.mkdirs();
        }
        outputFile = new File(outputDir, reponseFilename);
    } else {
        // 
        File outputDir = new File(this.responseDir, SUB_DIR_FOR_SEMI_WRONG);
        outputFile = new File(outputDir, reponseFilename);
        if (!outputDir.exists()) {
            log.info("create directory: " + outputDir.getAbsolutePath());
            outputDir.mkdirs();
        }
    }

    log.info("output reponse file: " + outputFile.getAbsolutePath());

    // 
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    RequestHeader header = RequestHeader.parseHeaderInfo(this.requestFile);
    Writer writer = new FileWriter(outputFile);
    writer.write(header.getSerialNumber());
    writer.write('\t');
    writer.write(header.getVersion());
    writer.write('\t');
    writer.write(format.format(new Date()));
    writer.write('\t');
    writer.write("");
    writer.write('\t');
    writer.write(this.totalRecords);
    writer.write('\t');
    writer.write(this.successRecords);
    writer.write('\t');
    writer.write('\n');

    if (this.totalRecords != this.successRecords && this.totalRecords != this.errorRecords) {
        // 
        FileReader in = new FileReader(this.bodyFile);
        char[] buf = new char[512];
        int len = in.read(buf);
        while (len > 0) {
            writer.write(buf, 0, len);
            len = in.read(buf);
        }
        in.close();
    }

    writer.close();
}

From source file:org.midonet.midolman.Setup.java

protected void setupTrafficPriorityQdiscsNova() throws IOException, InterruptedException, URISyntaxException {
    FileReader confFile = new FileReader("/etc/nova/nova.conf");
    char[] confBytes = new char[5000];
    int confByteLength = confFile.read(confBytes);
    String[] allArgs = (new String(confBytes, 0, confByteLength)).split("\n");
    for (String arg : allArgs) {
        // RabbitMQ
        if (arg.startsWith("--rabbit_host")) {
            String[] flaghost = arg.split("=");
            setupTrafficPriorityRule(flaghost[1], "5672");
        }//from  w  w w  .j av a  2 s . c o m

        // mysql
        if (arg.startsWith("--sql_connection")) {
            String[] flagurl = arg.split("=");
            URI mysqlUrl = new URI(flagurl[1]);
            int port = mysqlUrl.getPort();
            if (port == -1)
                port = 3306;
            setupTrafficPriorityRule(mysqlUrl.getHost(), Integer.toString(port));
        }

        // VNC
        if (arg.startsWith("--sql_connection")) {
            String[] flagurl = arg.split("=");
            URI vncUrl = new URI(flagurl[1]);
            int port = vncUrl.getPort();
            if (port == -1)
                port = 6080;
            setupTrafficPriorityRule(vncUrl.getHost(), Integer.toString(port));
        }

        // EC2
        if (arg.startsWith("--ec2_url")) {
            String[] flagurl = arg.split("=");
            URI ec2Url = new URI(flagurl[1]);
            int port = ec2Url.getPort();
            if (port == -1)
                port = 8773;
            setupTrafficPriorityRule(ec2Url.getHost(), Integer.toString(port));
        }
    }
}

From source file:org.apache.vxquery.xtest.TestCaseResult.java

private String slurpFile(File f) {
    StringWriter out = new StringWriter();
    try {/*w w  w.  j  a va2  s  . com*/
        FileReader in = new FileReader(f);
        try {
            char[] buffer = new char[8192];
            int c;
            while ((c = in.read(buffer)) >= 0) {
                out.write(buffer, 0, c);
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    } catch (IOException e) {
        return null;
    }
    return out.toString();
}

From source file:de.pdark.dsmp.ProxyDownload.java

/**
 * Do the download.//from  w  w  w. ja  v a  2  s.c  o  m
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in DSMP config");
    }

    // If there is a status file in the cache, return it instead of trying it again
    // As usual with caches, this one is a key area which will always cause
    // trouble.
    // TODO There should be a simple way to get rid of the cached statuses
    // TODO Maybe retry a download after a certain time?
    File statusFile = new File(dest.getAbsolutePath() + ".status");
    if (statusFile.exists()) {
        try {
            FileReader r = new FileReader(statusFile);
            char[] buffer = new char[(int) statusFile.length()];
            int len = r.read(buffer);
            r.close();
            String status = new String(buffer, 0, len);
            throw new DownloadFailed(status);
        } catch (IOException e) {
            log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
        }
    }

    mkdirs();

    HttpClient client = new HttpClient();

    String msg = "";
    if (config.useProxy(url)) {
        Credentials defaultcreds = new UsernamePasswordCredentials(config.getProxyUsername(),
                config.getProxyPassword());
        AuthScope scope = new AuthScope(config.getProxyHost(), config.getProxyPort(), AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(config.getProxyHost(), config.getProxyPort());
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + "to " + dest.getAbsolutePath());

    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    try {
        int status = client.executeMethod(get);

        log.info("Download status: " + status);
        if (0 == 1 && log.isDebugEnabled()) {
            Header[] header = get.getResponseHeaders();
            for (Header aHeader : header)
                log.debug(aHeader.toString().trim());
        }

        log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(get.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            // Remember "File not found"
            if (status == HttpStatus.SC_NOT_FOUND) {
                try {
                    FileWriter w = new FileWriter(statusFile);
                    w.write(get.getStatusLine().toString());
                    w.close();
                } catch (IOException e) {
                    log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
                }
            }
            throw new DownloadFailed(get);
        }

        File dl = new File(dest.getAbsolutePath() + ".new");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        IOUtils.copy(get.getResponseBodyAsStream(), out);
        out.close();

        File bak = new File(dest.getAbsolutePath() + ".bak");
        if (bak.exists())
            bak.delete();
        if (dest.exists())
            dest.renameTo(bak);
        dl.renameTo(dest);
    } finally {
        get.releaseConnection();
    }
}

From source file:org.rhq.plugins.mysql.MySqlComponent.java

private long findPID() {
    long result = -1;
    String pidFile = globalVariables.get("PID_FILE");
    File file = new File(pidFile);
    if (file.canRead()) {
        try {//from w  w  w.  ja  v a2  s.  co m
            FileReader pidFileReader = new FileReader(file);
            try {
                char pidData[] = new char[(int) file.length()];
                pidFileReader.read(pidData);
                String pidString = new String(pidData);
                pidString = pidString.trim();
                result = Long.valueOf(pidString);
            } finally {
                pidFileReader.close();
            }
        } catch (Exception ex) {
            log.warn("Unable to read MySQL pid file " + pidFile);
        }
    }
    return result;
}

From source file:org.faul.jql.core.JCommon.java

/**
 * Load data from a file into a List of HashMaps.
 * @param fr FileReader. The filereader to load the data from.
 * @return List. The database table, a List of Maps.
 * @throws Exception. throws exceptions on File IO and Gson encoding errors.
 *//*from   www  .j  a v a  2  s.  c  om*/
List loadFile(FileReader fr) throws Exception {
    char[] buf = new char[4096];
    String data = null;
    int rc = fr.read(buf);
    fr.close();
    data = new String(buf, 0, rc);
    Object rets = mapper.readValue((String) data, Object.class);
    if (rets instanceof ArrayList == false) {
        throw new Exception("List class not returned!");
    }
    return (List) rets;
}

From source file:com.amazonaws.mturk.cmd.MakeTemplate.java

private void copyTemplateFile(String sourceRoot, String targetRoot, String extension) throws Exception {
    String inputFileName = sourceRoot + extension;
    String outputFileName = targetRoot + extension;

    System.out.println("Copying resource file: " + outputFileName);

    File inputFile = new File(inputFileName);
    if (!inputFile.exists() || !inputFile.canRead()) {
        throw new Exception("Could not read from the file " + inputFileName);
    }/*from w  w w. j  a v  a2s .  c o  m*/

    File outputFile = new File(outputFileName);
    if (!outputFile.exists()) {
        if (!outputFile.createNewFile() || !outputFile.canWrite())
            throw new Exception("Could not write to the file " + outputFileName);
    }

    // copy file
    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);

    try {
        char[] buffer = new char[1024];
        int nread = 0;
        while ((nread = in.read(buffer)) != -1) {
            out.write(buffer, 0, nread);
        }
    } finally {
        in.close();
        out.close();
    }
}

From source file:org.walkmod.writers.AbstractFileWriter.java

public char getEndLineChar(File file) throws IOException {
    char endLineChar = '\n';
    if (file.exists()) {
        FileReader reader = new FileReader(file);
        try {/*from w w w . jav a  2s .c o m*/
            char[] buffer = new char[150];
            boolean detected = false;
            int bytes = reader.read(buffer);
            char previousChar = '\0';
            while (bytes > 0 && !detected) {
                for (int i = 0; i < bytes && !detected; i++) {
                    if (buffer[i] == '\r') {
                        endLineChar = '\r';
                        detected = true;
                    }
                    detected = detected || (previousChar == '\n' && buffer[i] != '\r');
                    previousChar = buffer[i];

                }
                if (!detected) {
                    bytes = reader.read(buffer);
                }
            }
        } finally {
            reader.close();
        }
    } else {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("windows")) {
            endLineChar = '\r';
        }
    }
    return endLineChar;
}

From source file:br.ufjf.taverna.core.TavernaClientBase.java

protected HttpURLConnection request(String endpoint, TavernaServerMethods method, int expectedResponseCode,
        String acceptData, String contentType, String filePath, String putData) throws TavernaException {
    HttpURLConnection connection = null;

    try {/*w w  w. j a  va2  s.  co  m*/
        String uri = this.getBaseUri() + endpoint;
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        String authorization = this.username + ":" + this.password;
        String encodedAuthorization = "Basic " + new String(Base64.encodeBase64(authorization.getBytes()));
        connection.setRequestProperty("Authorization", encodedAuthorization);
        connection.setRequestMethod(method.getMethod());

        if (acceptData != null) {
            connection.setRequestProperty("Accept", acceptData);
        }

        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }

        if (TavernaServerMethods.GET.equals(method)) {

        } else if (TavernaServerMethods.POST.equals(method)) {
            FileReader fr = new FileReader(filePath);
            char[] buffer = new char[1024 * 10];
            int read;
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            while ((read = fr.read(buffer)) != -1) {
                writer.write(buffer, 0, read);
            }
            writer.flush();
            writer.close();
            fr.close();
        } else if (TavernaServerMethods.PUT.equals(method)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(putData);
            writer.flush();
            writer.close();
        } else if (TavernaServerMethods.DELETE.equals(method)) {

        }

        int responseCode = connection.getResponseCode();
        if (responseCode != expectedResponseCode) {
            throw new TavernaException(
                    String.format("Invalid HTTP Response Code. Expected %d, actual %d, URL %s",
                            expectedResponseCode, responseCode, url));
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return connection;
}

From source file:mendeley2kindle.KindleDAO.java

public void open(String kindleLocal) throws IOException, JSONException {
    this.kindleLocal = kindleLocal;

    File path = new File(kindleLocal);
    File file = new File(path, KINDLE_COLLECTIONS_JSON);
    log.log(Level.FINER, "Loading collections data: " + file);
    if (file.exists() && file.canRead()) {
        FileReader fr = new FileReader(file);
        StringBuilder sb = new StringBuilder();
        char[] buf1 = new char[2048];
        for (int read = 0; (read = fr.read(buf1)) > 0;)
            sb.append(buf1, 0, read);/*from  w  w w  .  j a va  2  s.  co  m*/

        collections = new JSONObject(sb.toString());
        log.log(Level.FINE, "Loaded kindle collections: " + path);
    } else {
        log.log(Level.FINE, "Kindle collections data " + file + " not found. Creating...");
        collections = new JSONObject();
    }
    isOpened = true;
}