Example usage for java.io InputStreamReader ready

List of usage examples for java.io InputStreamReader ready

Introduction

In this page you can find the example usage for java.io InputStreamReader ready.

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:Main.java

public static void main(String[] args) throws IOException {

    int i;//www.  j a  v  a 2s  . c  o  m

    FileInputStream fis = new FileInputStream("C:/test.txt");
    InputStreamReader isr = new InputStreamReader(fis);

    while ((i = isr.read()) != -1) {
        char c = (char) i;
        System.out.println("Character read: " + c);
        // true if the next read is guaranteed
        boolean bool = isr.ready();

        System.out.println("Ready to read: " + bool);
    }
}

From source file:eu.project.ttc.tools.cli.TermSuiteCLIUtils.java

/**
 * Read the standard input as a string.//ww  w  .j  ava 2 s .  c  om
 * @return
 * @throws IOException
 */
public static String readIn(String encoding) throws IOException {
    if (in == null) {
        InputStreamReader reader = new InputStreamReader(System.in, encoding);
        List<Character> chars = new LinkedList<Character>();
        int c;
        while (reader.ready() && ((c = reader.read()) != -1))
            chars.add((char) c);

        char[] charAry = new char[chars.size()];
        for (int i = 0; i < chars.size(); i++)
            charAry[i] = chars.get(i);
        in = new String(charAry);
    }
    return in;
}

From source file:forge.quest.io.QuestDataIO.java

/**
 * <p>/*from   ww  w  .j av a  2s . c  om*/
 * loadData.
 * </p>
 *
 * @param xmlSaveFile
 *            &emsp; {@link java.io.File}
 * @return {@link forge.quest.data.QuestData}
 */
public static QuestData loadData(final File xmlSaveFile) {
    try {
        QuestData data;

        final GZIPInputStream zin = new GZIPInputStream(new FileInputStream(xmlSaveFile));
        final StringBuilder xml = new StringBuilder();
        final char[] buf = new char[1024];
        final InputStreamReader reader = new InputStreamReader(zin);
        while (reader.ready()) {
            final int len = reader.read(buf);
            if (len == -1) {
                break;
            } // when end of stream was reached
            xml.append(buf, 0, len);
        }

        zin.close();

        String bigXML = xml.toString();
        data = (QuestData) QuestDataIO.getSerializer(true).fromXML(bigXML);

        if (data.getVersionNumber() != QuestData.CURRENT_VERSION_NUMBER) {
            try {
                QuestDataIO.updateSaveFile(data, bigXML, xmlSaveFile.getName().replace(".dat", ""));
            } catch (final Exception e) {
                //BugReporter.reportException(e);
                throw new RuntimeException(e);
            }
        }

        return data;
    } catch (final Exception ex) {
        //BugReporter.reportException(ex, "Error loading Quest Data");
        throw new RuntimeException(ex);
    }
}

From source file:com.jadarstudios.rankcapes.forge.cape.CapePack.java

/**
 * Parses the Zip file in memory./*from  www . ja  v  a  2 s .  c  o m*/
 *
 * @param input the bytes of a valid zip file
 */
private void parsePack(byte[] input) {
    try {
        ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(input));

        String metadata = "";

        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            String name = entry.getName();

            if (name.endsWith(".png")) {
                // remove file extension from the name.
                name = FilenameUtils.removeExtension(name);

                StaticCape cape = this.loadCape(name, zipInput);
                this.unprocessedCapes.put(name, cape);
            } else if (name.endsWith(".mcmeta")) {
                // parses the pack metadata.
                InputStreamReader streamReader = new InputStreamReader(zipInput);
                while (streamReader.ready()) {
                    metadata += (char) streamReader.read();
                }
            }
        }
        if (!Strings.isNullOrEmpty(metadata)) {
            this.parsePackMetadata(StringUtils.remove(metadata, (char) 65535));
        } else {
            RankCapesForge.log.warn("Cape Pack metadata is missing!");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.navjagpal.fileshare.WebServer.java

private void handleLoginRequest(DefaultHttpServerConnection serverConnection, HttpRequest request,
        RequestLine requestLine) throws HttpException, IOException {

    BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest(
            request.getRequestLine());//from w  ww.ja  v  a 2  s . c o  m
    serverConnection.receiveRequestEntity(enclosingRequest);

    InputStream input = enclosingRequest.getEntity().getContent();
    InputStreamReader reader = new InputStreamReader(input);

    StringBuffer form = new StringBuffer();
    while (reader.ready()) {
        form.append((char) reader.read());
    }
    String password = form.substring(form.indexOf("=") + 1);
    if (password.equals(mSharedPreferences.getString(FileSharingService.PREFS_PASSWORD, ""))) {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 302, "Found");
        response.addHeader("Location", "/");
        response.addHeader("Set-Cookie", "id=" + createCookie());
        response.setEntity(new StringEntity(getHTMLHeader() + "Success!" + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    } else {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 401, "Unauthorized");
        response.setEntity(
                new StringEntity(getHTMLHeader() + "<p>Login failed.</p>" + getLoginForm() + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    }
}

From source file:ut.ee.mh.WebServer.java

private void handleLocationRequest(DefaultHttpServerConnection serverConnection, HttpRequest request,
        RequestLine requestLine) throws HttpException, IOException {

    BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest(
            request.getRequestLine());/*from   w w w.  jav a2 s  . c om*/
    serverConnection.receiveRequestEntity(enclosingRequest);

    InputStream input = enclosingRequest.getEntity().getContent();
    InputStreamReader reader = new InputStreamReader(input);

    StringBuffer form = new StringBuffer();
    while (reader.ready()) {
        form.append((char) reader.read());
    }
    String password = form.substring(form.indexOf("=") + 1);

    if (password.equals(mSharedPreferences.getString(FileSharingService.PREFS_PASSWORD, ""))) {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 302, "Found");
        response.addHeader("Location", "/");
        response.addHeader("Set-Cookie", "id=" + createCookie());
        response.setEntity(new StringEntity(getHTMLHeader() + "Success!" + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    } else {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 401, "Unauthorized");
        response.setEntity(
                new StringEntity(getHTMLHeader() + "<p>Login failed.</p>" + getLoginForm() + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    }
}

From source file:de.gfz_potsdam.datasync.Datasync.java

public void sync() throws Exception {

    srv.init();/*from   www.j ava  2  s  . co  m*/

    InputStreamReader r = new InputStreamReader(System.in);
    int i = 0;
    while (!r.ready()) {
        Thread.sleep(1000);
        try {
            log.log(Level.INFO, "Pass {0}", new Object[] { i });
            srv.init();
            srv.update();
            traverseServerAndDownload(new String(), srv.getTopContainer());
            traverseServerAndDeleteLocal(new String(), srv.getTopContainer());
            traverseLocalAndUpload(new String(), srv.getTopContainer().getProperties().getName());
            srv.update();
            traverseLocalAndDeleteRemote(new String(), srv.getTopContainer().getProperties().getName());
            i++;
        } catch (ResourceNotFoundException e) {
            System.out.println("Resource not found - Server state changed");
            e.printStackTrace();
        }
    }
}

From source file:com.motorola.studio.android.utilities.TelnetFrameworkAndroid.java

/**
 *
 *//*from  w  w  w  .ja v a  2 s.com*/
public String waitFor(String[] waitForArray) throws IOException {
    InputStreamReader responseReader = null;
    StringBuffer answerFromRemoteHost = new StringBuffer();

    try {
        responseReader = new InputStreamReader(telnetClient.getInputStream());

        boolean found = false;

        do {
            char readChar = 0;
            long currentTime = System.currentTimeMillis();
            long timeoutTime = currentTime + timeout;

            while (readChar == 0) {
                if (responseReader == null) {
                    // responseReader can only be set to null if method
                    // releaseTelnetInputStreamReader()
                    // has been called, which should happen if host becomes
                    // unavailable.
                    throw new IOException("Telnet host is unavailable; stopped waiting for answer.");
                }

                if (responseReader.ready()) {
                    readChar = (char) responseReader.read();
                } else {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        // Do nothing
                    }
                }

                currentTime = System.currentTimeMillis();

                if ((!responseReader.ready()) && (currentTime > timeoutTime)) {
                    throw new IOException("A timeout has occured when trying to read the telnet stream");
                }
            }

            answerFromRemoteHost.append(readChar);

            for (String aWaitFor : waitForArray) {
                found = answerFromRemoteHost.toString().contains(aWaitFor);
            }

        } while (!found);
    } finally {
        if (responseReader != null) {
            responseReader.close();
        }
    }

    return answerFromRemoteHost.toString();
}

From source file:org.acmsl.commons.utils.io.IOUtils.java

/**
 * Reads given input stream into a String.
 * @param inputStream the input stream to read.
 * @param contentLength the length of the content.
 * @param charset the charset.//from  w  ww. j  ava  2s . c o  m
 * @return the input stream contents, or an empty string if the operation
 * fails.
 * @exception IOException if the input stream cannot be read.
 */
@NotNull
public String read(@NotNull final InputStream inputStream, final int contentLength,
        @NotNull final Charset charset) throws IOException {
    @NotNull
    final StringBuilder t_sbResult = new StringBuilder();

    @NotNull
    final CharUtils t_CharUtils = CharUtils.getInstance();

    if (contentLength > 0) {
        @NotNull
        final InputStreamReader t_isrReader = new InputStreamReader(inputStream, charset);

        @NotNull
        char[] t_acContents = new char[contentLength];

        int bytesRead = 0;
        int totalBytesRead = 0;

        if (t_isrReader.ready()) {
            while (totalBytesRead < contentLength) {
                bytesRead = t_isrReader.read(t_acContents);

                totalBytesRead += bytesRead;

                if (bytesRead < contentLength) {
                    @NotNull
                    final char[] aux = new char[bytesRead];
                    System.arraycopy(t_acContents, 0, aux, 0, bytesRead);
                    t_sbResult.append(aux);
                    t_acContents = new char[contentLength - bytesRead];
                }
            }
        }

        t_sbResult.append(t_acContents);
    } else {
        @NotNull
        final InputStreamReader t_isrReader = new InputStreamReader(inputStream, charset);

        @NotNull
        final char[] t_acContents = new char[BLOCK_SIZE];

        while (t_isrReader.ready()) {
            final int t_iCharsRead = t_isrReader.read(t_acContents);

            @NotNull
            final char[] t_acCharsRead = (t_iCharsRead == BLOCK_SIZE) ? t_acContents
                    : t_CharUtils.subbuffer(t_acContents, 0, t_iCharsRead);

            t_sbResult.append(t_acCharsRead);
        }
    }

    return t_sbResult.toString();
}

From source file:org.kalypso.optimize.SceJob.java

private void startSCEOptimization(final SceIOHandler sceIO, final ISimulationMonitor monitor)
        throws SimulationException {
    InputStreamReader inStream = null;
    InputStreamReader errStream = null;

    // FIXME: too much copy/paste from ProcessHelper; we can probably use process helper instead!
    ProcessControlThread procCtrlThread = null;
    try {/*from  w  ww.j a  v a  2 s.c o m*/
        final String[] commands = new String[] { m_sceExe.getAbsolutePath() };

        final Process process = Runtime.getRuntime().exec(commands, null, m_sceDir);
        final long lTimeOut = 1000l * 60l * 15l;// 15 minutes
        procCtrlThread = new ProcessControlThread(process, lTimeOut);
        procCtrlThread.start();

        final StringBuffer outBuffer = new StringBuffer();
        final StringBuffer errBuffer = new StringBuffer();

        final Writer inputWriter = new PrintWriter(process.getOutputStream(), false);

        inStream = new InputStreamReader(process.getInputStream());
        errStream = new InputStreamReader(process.getErrorStream());

        final int stepMax = m_autoCalibration.getOptParameter().getMaxN();

        while (true) {
            final int step = sceIO.getStep();
            monitor.setProgress(100 * step / (stepMax + 1));
            if (step > stepMax) {
                final String monitorMsg = String.format(
                        "Optimierungsrechnung abgeschlossen, Ergebnisauswertung", step + 1, stepMax + 1);
                monitor.setMessage(monitorMsg);
            } else {
                final String monitorMsg = String.format("Optimierungsrechnung %d von %d", step + 1,
                        stepMax + 1);
                monitor.setMessage(monitorMsg);
            }

            if (inStream.ready()) {
                final char buffer[] = new char[100];
                final int bufferC = inStream.read(buffer);
                outBuffer.append(buffer, 0, bufferC);
            }
            if (errStream.ready()) {
                final char buffer[] = new char[100];
                final int bufferC = errStream.read(buffer);
                errBuffer.append(buffer, 0, bufferC);
            }
            if (monitor.isCanceled()) {
                process.destroy();
                procCtrlThread.endProcessControl();
                return;
            }
            try {
                process.exitValue();
                break;
            } catch (final IllegalThreadStateException e) {
                final OptimizeMonitor subMonitor = new OptimizeMonitor(monitor);
                sceIO.handleStreams(outBuffer, errBuffer, inputWriter, subMonitor);
            }
            Thread.sleep(100);
        }

        procCtrlThread.endProcessControl();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new SimulationException("Fehler beim Ausfuehren", e);
    } catch (final InterruptedException e) {
        e.printStackTrace();
        throw new SimulationException("beim Ausfuehren unterbrochen", e);
    } finally {
        IOUtils.closeQuietly(inStream);
        IOUtils.closeQuietly(errStream);
        if (procCtrlThread != null && procCtrlThread.procDestroyed()) {
            throw new SimulationException("beim Ausfuehren unterbrochen",
                    new ProcessTimeoutException("Timeout bei der Abarbeitung der Optimierung"));
        }
    }
}