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:i2p.bote.I2PBote.java

/**
 * Sets up a {@link I2PSession}, using the I2P destination stored on disk or creating a new I2P
 * destination if no key file exists.//from  ww w . jav  a  2 s  . co  m
 */
private void initializeSession() throws I2PSessionException {
    Properties sessionProperties = new Properties();
    // set tunnel names
    sessionProperties.setProperty("inbound.nickname", "I2P-Bote");
    sessionProperties.setProperty("outbound.nickname", "I2P-Bote");
    if (configuration.isI2CPDomainSocketEnabled())
        sessionProperties.setProperty("i2cp.domainSocket", "true");
    // According to sponge, muxed depends on gzip, so leave gzip enabled

    // read the local destination key from the key file if it exists
    File destinationKeyFile = configuration.getDestinationKeyFile();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(destinationKeyFile);
        char[] destKeyBuffer = new char[(int) destinationKeyFile.length()];
        fileReader.read(destKeyBuffer);
        byte[] localDestinationKey = Base64.decode(new String(destKeyBuffer));
        ByteArrayInputStream inputStream = new ByteArrayInputStream(localDestinationKey);
        socketManager = I2PSocketManagerFactory.createDisconnectedManager(inputStream, null, 0,
                sessionProperties);
    } catch (IOException e) {
        log.debug("Destination key file doesn't exist or isn't readable." + e);
    } catch (I2PSessionException e) {
        // Won't happen, inputStream != null
    } finally {
        if (fileReader != null)
            try {
                fileReader.close();
            } catch (IOException e) {
                log.debug("Error closing file: <" + destinationKeyFile.getAbsolutePath() + ">" + e);
            }
    }

    // if the local destination key can't be read or is invalid, create a new one
    if (socketManager == null) {
        log.debug("Creating new local destination key");
        try {
            ByteArrayOutputStream arrayStream = new ByteArrayOutputStream();
            i2pClient.createDestination(arrayStream);
            byte[] localDestinationKey = arrayStream.toByteArray();

            ByteArrayInputStream inputStream = new ByteArrayInputStream(localDestinationKey);
            socketManager = I2PSocketManagerFactory.createDisconnectedManager(inputStream, null, 0,
                    sessionProperties);

            saveLocalDestinationKeys(destinationKeyFile, localDestinationKey);
        } catch (I2PException e) {
            log.error("Error creating local destination key.", e);
        } catch (IOException e) {
            log.error("Error writing local destination key to file.", e);
        }
    }

    i2pSession = socketManager.getSession();
    // Throws I2PSessionException if the connection fails
    i2pSession.connect();

    Destination localDestination = i2pSession.getMyDestination();
    log.info("Local destination key (base64): " + localDestination.toBase64());
    log.info("Local destination hash (base64): " + localDestination.calculateHash().toBase64());
    log.info("Local destination hash (base32): " + Util.toBase32(localDestination));
}

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

/**
 * Given a filename, read it into a string buffer.
 * @param fileName. String. The name of the file to load.
 * @return String. The contents of the file that was read.
 * @throws Exception. Throws exception on I/O errors.
 *//*  ww  w.j a v a 2  s.  c o  m*/
public String readFile(String fileName) throws Exception {
    String data = "";
    FileReader fr = new FileReader(fileName);
    char[] buf = new char[4096];
    int i = 1;
    while (i > 0) {
        i = fr.read(buf);
        if (i > 0)
            data += new String(buf, 0, i);
    }
    return data;
}

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

/**
 * Retrieve a CSV file, convert to Maps and append them to the given List.
 * // ww w. ja v a2 s.c  o m
 * @param list
 *            List<Map>. The list to append the CSV file onto.
 * @param fr
 *            FileReader. The file reader of the CSV file.
 * @throws Exception. Throws
 *             exceptions on I/O errors
 */
public void fromCSV(List<Map> list, FileReader fr) throws Exception {
    String data = "";
    char buf[] = new char[4096];
    int rc = 1;
    while (rc > 0) {
        rc = fr.read(buf);
        data += new String(buf, 0, rc);
    }
    fromCSV(list, data);
}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * <p>Read a text file and returns a character array with it</p>
 * Enconding is UTF-8 by default/* w  w  w  .  j  a va2 s.c  o m*/
 * @param sFilePath Full path of file to be readed. Like "file:///tmp/myfile.txt" or "ftp://myhost:21/dir/myfile.txt"
 * @return character array with full contents of file
 * @throws FileNotFoundException
 * @throws IOException
 * @throws OutOfMemoryError
 * @throws FTPException
 */
public static char[] readfile(String sFilePath)
        throws FileNotFoundException, IOException, OutOfMemoryError, FTPException {

    if (DebugFile.trace) {
        DebugFile.writeln("Begin FileSystem.readfile(" + sFilePath + ")");
        DebugFile.incIdent();
    }

    char[] aBuffer;
    String sLower = sFilePath.toLowerCase();

    if (sLower.startsWith("file://"))
        sFilePath = sFilePath.substring(7);

    if (sLower.startsWith("http://") || sLower.startsWith("https://") || sLower.startsWith("ftp://")) {
        aBuffer = new FileSystem().readfilestr(sFilePath, "UTF-8").toCharArray();
    } else {
        File oFile = new File(sFilePath);

        aBuffer = new char[(int) oFile.length()];

        FileReader oReader = new FileReader(oFile);

        oReader.read(aBuffer);

        oReader.close();

        oReader = null;
        oFile = null;
    }

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.readfile() : " + String.valueOf(aBuffer.length));
    }

    return aBuffer;
}

From source file:org.clipsmonitor.core.MonitorGenMap.java

@SuppressWarnings("UnnecessaryUnboxing")
private void LoadJsonMap(File jsonFile) throws ParseException {
    //creo una nuova istanza di scena

    try {//from ww w  .  j av a 2s  .c o  m
        //converto il file in un oggetto JSON
        FileReader jsonreader = new FileReader(jsonFile);
        char[] chars = new char[(int) jsonFile.length()];
        jsonreader.read(chars);
        String jsonstring = new String(chars);
        jsonreader.close();
        JSONObject json = new JSONObject(jsonstring);
        //leggo il numero di celle dalla radice del JSON

        int NumCellX = Integer.parseInt(json.get("cell_x").toString());
        int NumCellY = Integer.parseInt(json.get("cell_y").toString());

        SetNumCell(NumCellX, NumCellY);
        SetSizeCells();

        //imposto la dimensione iniziale della scena
        scene = new String[NumCellX][NumCellY];
        //initScene(scene);
        move = clone(scene);

        //estraggo il JSONArray dalla radice
        JSONArray arrayCelle = json.getJSONArray("cells");
        for (int i = 0; i < arrayCelle.length(); i++) {
            //ciclo su ogni cella e setto il valore della cella letta nella scena
            JSONObject cell = arrayCelle.getJSONObject(i);
            int x = cell.getInt("x");
            int y = cell.getInt("y");
            String state = cell.getString("state");
            setCell(x, y, state);
        }

        CopyToActive(scene);

    } catch (JSONException ex) {

        AppendLogMessage(ex.getMessage(), "error");
    } catch (IOException ex) {
        AppendLogMessage(ex.getMessage(), "error");
    } catch (NumberFormatException ex) {
        AppendLogMessage(ex.getMessage(), "error");
    }

}

From source file:org.clipsmonitor.core.MonitorGenMap.java

public void LoadMoves(File jsonFile) throws ParseException {

    try {/*from ww  w  . ja  va 2s  .c o m*/
        //converto il file in un oggetto JSON
        FileReader jsonreader = new FileReader(jsonFile);
        char[] chars = new char[(int) jsonFile.length()];
        jsonreader.read(chars);
        String jsonstring = new String(chars);
        jsonreader.close();
        JSONObject json = new JSONObject(jsonstring);

        Persons = new LinkedList<Person>();

        //estraggo il JSONArray dalla radice
        JSONArray arrayPersons = json.getJSONArray("personList");
        for (int i = 0; i < arrayPersons.length(); i++) {

            JSONObject person = arrayPersons.getJSONObject(i);
            String color = person.getString("color");
            Person p = new Person(color);
            JSONArray arrayPaths = person.getJSONArray("paths");

            for (int j = 0; j < arrayPaths.length(); j++) {

                JSONObject path = arrayPaths.getJSONObject(j);
                String pathName = path.getString("name");
                int startStep = path.getInt("startStep");
                int lastStep = path.getInt("lastStep");
                p.paths.add(new Path(pathName, startStep, lastStep));
                JSONArray arrayMoves = path.getJSONArray("moves");

                for (int k = 0; k < arrayMoves.length(); k++) {

                    JSONObject move = arrayMoves.getJSONObject(k);
                    int x = move.getInt("x");
                    int y = move.getInt("y");
                    int step = move.getInt("step");
                    p.paths.getLast().move.add(new StepMove(x, y, step));
                }
            }
            Persons.add(p);
        }

        maxduration = json.getInt("time");

    } catch (JSONException ex) {
        AppendLogMessage(ex.getMessage(), "error");
    } catch (IOException ex) {
        AppendLogMessage(ex.getMessage(), "error");
    } catch (NumberFormatException ex) {
        AppendLogMessage(ex.getMessage(), "error");
    }

}

From source file:org.apache.hadoop.mapred.TaskLogsMonitor.java

/**
 * Truncate the log file of this task-attempt so that only the last retainSize
 * many bytes of each log file is retained and the log file is reduced in size
 * saving disk space./*from w  w  w  . j a v  a2s .  c  o  m*/
 * 
 * @param taskID Task whose logs need to be truncated
 * @param oldLogFileDetail contains the original log details for the attempt
 * @param taskRetainSize retain-size
 * @param tmpFileWriter New log file to write to. Already opened in append
 *          mode.
 * @param logFileReader Original log file to read from.
 * @return
 * @throws IOException
 */
private LogFileDetail truncateALogFileOfAnAttempt(final TaskAttemptID taskID,
        final LogFileDetail oldLogFileDetail, final long taskRetainSize, final FileWriter tmpFileWriter,
        final FileReader logFileReader) throws IOException {
    LogFileDetail newLogFileDetail = new LogFileDetail();

    // ///////////// Truncate log file ///////////////////////

    // New location of log file is same as the old
    newLogFileDetail.location = oldLogFileDetail.location;
    if (taskRetainSize > MINIMUM_RETAIN_SIZE_FOR_TRUNCATION && oldLogFileDetail.length > taskRetainSize) {
        LOG.info("Truncating logs for " + taskID + " from " + oldLogFileDetail.length + "bytes to "
                + taskRetainSize + "bytes.");
        newLogFileDetail.length = taskRetainSize;
    } else {
        LOG.info("No truncation needed for " + taskID + " length is " + oldLogFileDetail.length
                + " retain size " + taskRetainSize + "bytes.");
        newLogFileDetail.length = oldLogFileDetail.length;
    }
    long charsSkipped = logFileReader.skip(oldLogFileDetail.length - newLogFileDetail.length);
    if (charsSkipped != oldLogFileDetail.length - newLogFileDetail.length) {
        throw new IOException("Erroneously skipped " + charsSkipped + " instead of the expected "
                + (oldLogFileDetail.length - newLogFileDetail.length));
    }
    long alreadyRead = 0;
    while (alreadyRead < newLogFileDetail.length) {
        char tmpBuf[]; // Temporary buffer to read logs
        if (newLogFileDetail.length - alreadyRead >= DEFAULT_BUFFER_SIZE) {
            tmpBuf = new char[DEFAULT_BUFFER_SIZE];
        } else {
            tmpBuf = new char[(int) (newLogFileDetail.length - alreadyRead)];
        }
        int bytesRead = logFileReader.read(tmpBuf);
        if (bytesRead < 0) {
            break;
        } else {
            alreadyRead += bytesRead;
        }
        tmpFileWriter.write(tmpBuf);
    }
    // ////// End of truncating log file ///////////////////////

    return newLogFileDetail;
}