Example usage for java.io BufferedReader ready

List of usage examples for java.io BufferedReader ready

Introduction

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

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:net.pixhan.utilidades.OperacionesConArchivos.java

public static VariablesGlobales leerVariables(String ubicacionArchivo) throws IOException {

    File archivo = new File(ubicacionArchivo);
    //        byte[] org.apache.commons.io.FileUtils.readFileToByteArray( archivo );
    //        List lines = FileUtils.readLines(archivo, "UTF-8");

    boolean errorEncontrado = true;
    //        File archivo = new File( ubicacionArchivo );
    BufferedReader entrada;
    VariablesGlobales variablesGlobales = new VariablesGlobales();
    try {//  w ww  . ja  va  2  s  .  c o m
        entrada = new BufferedReader(new FileReader(archivo));
        if (entrada.ready()) {
            variablesGlobales.setNegocioBD(entrada.readLine());
            System.out.println(variablesGlobales.getNegocioBD());
        }
        if (entrada.ready()) {
            variablesGlobales.setNegocioUser(entrada.readLine());
        }
        if (entrada.ready()) {
            variablesGlobales.setNegocioPass(entrada.readLine());
        }
        if (entrada.ready()) {
            variablesGlobales.setNegocioHost(entrada.readLine());
        }
        if (entrada.ready()) {
            variablesGlobales.setSeguridadBD(entrada.readLine());
        }
        if (entrada.ready()) {
            variablesGlobales.setSeguridadUser(entrada.readLine());
        }
        if (entrada.ready()) {
            variablesGlobales.setSeguridadPass(entrada.readLine());
        }
        if (entrada.ready()) {
            variablesGlobales.setSeguridadHost(entrada.readLine());
            errorEncontrado = false;
        }
        if (errorEncontrado) {
            return null;
        } else {
            return variablesGlobales;
        }

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

    return null;

}

From source file:Main.java

private static List<Integer> getAllRelatedPids(final int pid) {
    List<Integer> result = new ArrayList<Integer>(Arrays.asList(pid));
    // use 'ps' to get this pid and all pids that are related to it (e.g.
    // spawned by it)
    try {/*  w ww.j  a  v  a2s. co  m*/

        final Process suProcess = Runtime.getRuntime().exec("su");

        new Thread(new Runnable() {

            @Override
            public void run() {
                PrintStream outputStream = null;
                try {
                    outputStream = new PrintStream(new BufferedOutputStream(suProcess.getOutputStream(), 8192));
                    outputStream.println("ps");
                    outputStream.println("exit");
                    outputStream.flush();
                } finally {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                }

            }
        }).run();

        if (suProcess != null) {
            try {
                suProcess.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(suProcess.getInputStream()), 8192);
            while (bufferedReader.ready()) {
                String[] line = SPACES_PATTERN.split(bufferedReader.readLine());
                if (line.length >= 3) {
                    try {
                        if (pid == Integer.parseInt(line[2])) {
                            result.add(Integer.parseInt(line[1]));
                        }
                    } catch (NumberFormatException ignore) {
                    }
                }
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    return result;
}

From source file:org.brunocvcunha.taskerbox.core.utils.TaskerboxFileUtils.java

/**
 * Imports lines to set// w ww .j  a  v a  2 s.c  o m
 *
 * @param action
 * @throws IOException
 */
public static Collection<String> deserializeMemory(ITaskerboxAction<?> action) throws IOException {
    if (getPerformedFileForAction(action).exists()) {
        log.debug("Deserializing history for channel " + action.getId());

        FileReader fr = new FileReader(getPerformedFileForAction(action));
        BufferedReader br = new BufferedReader(fr);

        Set<String> alreadyPerformed = new TreeSet<>();
        while (br.ready()) {
            alreadyPerformed.add(br.readLine());
        }
        br.close();

        return alreadyPerformed;
    } else {
        throw new IllegalArgumentException("There's nothing to deserialize for action " + action.getId());
    }
}

From source file:pt.webdetails.cdf.dd.packager.Concatenate.java

public static InputStream concat(File[] files, String rootpath) {
    if (rootpath == null || StringUtils.isEmpty(rootpath)) {
        return concat(files);
    }//from   w  ww . j a va 2  s. c  o m

    StringBuffer buffer = new StringBuffer();
    for (File file : files) {
        //TODO: review this!
        BufferedReader fr = null;
        try {
            StringBuffer tmp = new StringBuffer();
            fr = new BufferedReader(new FileReader(file));
            while (fr.ready()) {
                tmp.append(fr.readLine());
            }
            rootpath = rootpath.replaceAll("\\\\", "/").replaceAll("/+", "/");
            // Quick and dirty hack: if the path aims at the custom components, we point at getResource, else we point at the static resource folders

            String filePath = file.getPath().replaceAll("\\\\", "/"); // Fix windows slashes'
            String fileLocation = "";
            if (filePath.contains("resources/custom")) {
                fileLocation = filePath.replaceAll(file.getName(), "") // Remove this file's name
                        .replaceAll(rootpath, "../"); //
                //fileLocation = "";
            } else if (filePath.matches(".*pentaho-cdf-dd/css/.*/.*$")) {
                fileLocation = filePath.replaceAll(file.getName(), "") // Remove this file's name
                        .replaceAll(rootpath, "../");
            } else if (filePath.matches(".*cde/components/.*/.*$")) {
                fileLocation = "../../res/" + filePath.substring(filePath.indexOf("cde/components/"))
                        .replaceAll(file.getName() + "$", "");
            } else if (filePath.matches(".*system/c\\w\\w.*"))
                fileLocation = "../"
                        + filePath.substring(filePath.indexOf("system/")).replaceAll(file.getName() + "$", "");
            buffer.append(tmp.toString() //
                    // We need to replace all the URL formats
                    .replaceAll("(url\\(['\"]?)", "$1" + fileLocation.replaceAll("/+", "/"))); // Standard URLs
        } catch (FileNotFoundException e) {
            logger.error("concat: File " + file.getAbsolutePath() + " doesn't exist! Skipping...");
        } catch (Exception e) {
            logger.error("concat: Error while attempting to concatenate file " + file.getAbsolutePath()
                    + ". Trying to continue...", e);
        } finally {
            IOUtils.closeQuietly(fr);
        }

    }
    try {
        return new ByteArrayInputStream(buffer.toString().getBytes("UTF8"));
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        return null;
    }
}

From source file:Main.java

public static boolean isRooted() {
    Process p;//from w w  w  .j  a v a2  s  .  co m
    try {
        p = new ProcessBuilder("su").start();
        BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));

        stdin.write("whoami");
        stdin.newLine();
        stdin.write("exit");
        stdin.newLine();
        stdin.close();
        try {
            p.waitFor();
            if (!stdout.ready())
                return false;
            String user = stdout.readLine(); //We only expect one line of output
            stdout.close();
            if (user == "root") {
                return true;
            } else {
                return false;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:espresso.CsCompiler.java

public static String load(File file) throws IOException {
    BufferedReader fileReader = new BufferedReader(new FileReader(file));
    StringBuilder builder;//from   w w  w  .  j  a  v a2s.  c  o  m
    try {
        builder = new StringBuilder();
        while (fileReader.ready()) {
            builder.append(fileReader.readLine());
            builder.append("\n");
        }
        return builder.toString();

    } finally {
        fileReader.close();
    }
}

From source file:org.opennms.web.rest.KscRestServiceTest.java

private static String slurp(final File file) throws Exception {
    Reader fileReader = null;/*from ww  w.jav  a 2s  .  c o  m*/
    BufferedReader reader = null;

    try {
        fileReader = new FileReader(file);
        reader = new BufferedReader(fileReader);
        final StringBuilder sb = new StringBuilder();
        while (reader.ready()) {
            final String line = reader.readLine();
            System.err.println(line);
            sb.append(line).append('\n');
        }

        return sb.toString();
    } finally {
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(fileReader);
    }
}

From source file:org.fiware.apps.repository.it.collectionService.CollectionServiceGetITTest.java

@BeforeClass
public static void setUpClass() throws IOException {
    IntegrationTestHelper client = new IntegrationTestHelper();

    String fileName = "fileNameExample";
    String contentUrl = "http://localhost:8080/contentUrl/resourceTestGet";
    String creator = "Me";
    String name = "resourceTest";
    Resource resource = IntegrationTestHelper.generateResource(null, fileName, null, contentUrl, null, creator,
            null, null, name);//from   w w  w.  j av a 2 s .  c  o  m

    String auxString = "";
    FileReader file = new FileReader("src/test/resources/rdf+xml.rdf");
    BufferedReader buffer = new BufferedReader(file);
    while (buffer.ready()) {
        auxString = auxString.concat(buffer.readLine());
    }
    buffer.close();
    rdfxmlExample = auxString;

    //Delete the collection
    List<Header> headers = new LinkedList<>();
    client.deleteCollection(collection, headers);

    //Create a resource in the repository
    headers.add(new BasicHeader("Content-Type", "application/json"));
    HttpResponse response = client.postResourceMeta(collection, client.resourceToJson(resource), headers);
    assertEquals(201, response.getStatusLine().getStatusCode());

    //Insert RDF content in the resource
    headers = new LinkedList<>();
    headers.add(new BasicHeader("Content-Type", "application/rdf+xml"));
    response = client.putResourceContent(collection + "/" + name, rdfxmlExample, headers);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:Servlet.ServImportacaoMovVisual.java

public static String importaMovimento(FileItem item, Date dataIni, String nomeBD, int idUsuario) {

    int linha = 0;
    int qtdMov = 0;
    int qtdServ = 0;

    ArrayList<String> listaQuerys = new ArrayList<String>();
    ArrayList<String> listaIDS = new ArrayList<String>();

    String sqlBase = "INSERT INTO visual_movimento (data, cliente, codCliente, codServico, numObjeto, nomeDestinatario, cep, campo1, campo2, campo3"
            + ", valorAdicional, inteiro2, valor1, campo4, inteiro3, valor2, campo5, campo6, campo7, campo8) VALUES ";
    String sqlBaseServ = "REPLACE INTO visual_servicos (id, nomeServ, sto) VALUES ";

    StringBuilder sqlValues = new StringBuilder();
    StringBuilder sqlValuesServ = new StringBuilder();
    try {//from   w  ww . j a v a2  s . c o  m
        InputStreamReader is = new InputStreamReader(item.getInputStream(), Charset.forName("ISO-8859-1"));
        BufferedReader le = new BufferedReader(is);
        while (le.ready()) {
            linha++;
            String buffer = le.readLine().trim();
            if (buffer.startsWith("1")) {
                if (!buffer.endsWith("'20911424' )")) {
                    qtdMov++;
                    sqlValues.append(buffer.substring(1)).append(",");
                    if (qtdMov % 500 == 0) {
                        String sqlQuery = sqlBase
                                + sqlValues.substring(0, sqlValues.toString().lastIndexOf(","));// + sqlDuplicated;
                        listaQuerys.add(sqlQuery);
                        sqlValues = new StringBuilder();
                    }
                }
            } else if (buffer.startsWith("4")) {
                qtdServ++;
                sqlValuesServ.append(buffer.substring(1).replace(", '' )", ")")).append(",");
                if (qtdServ % 500 == 0) {
                    String sqlQuery = sqlBaseServ
                            + sqlValuesServ.substring(0, sqlValuesServ.toString().lastIndexOf(","));// + sqlDuplicated;
                    listaQuerys.add(sqlQuery);
                    sqlValuesServ = new StringBuilder();
                }

            }
        }
        le.close();

        if (!sqlValues.toString().equals("")) {
            String sqlQuery = sqlBase + sqlValues.substring(0, sqlValues.toString().lastIndexOf(","));// + sqlDuplicated;
            listaQuerys.add(sqlQuery);
        }
        if (!sqlValuesServ.toString().equals("")) {
            String sqlQuery = sqlBaseServ
                    + sqlValuesServ.substring(0, sqlValuesServ.toString().lastIndexOf(","));// + sqlDuplicated;
            listaQuerys.add(sqlQuery);
        }

        Controle.contrMovimentacao.importarMovVisual(listaIDS, listaQuerys, sqlBase, dataIni, nomeBD,
                idUsuario);

        return "Movimentao Importada Com Sucesso!";

    } catch (IOException e) {
        return "Erro na linha <b style='color:red;'>" + linha
                + "</b> do arquivo!<br><br>Falha: No foi possivel ler o arquivo!<br>Detalhes:" + e;
    } catch (Exception e) {
        return "Erro na linha <b style='color:red;'>" + linha
                + "</b> do arquivo!<br><br>Falha: Problema no tratamento do arquivo!<br>Detalhes: " + e;
    }

}

From source file:com.github.pitzcarraldo.openjpeg.OpenJPEGLoader.java

/**
 * Method to load a JP2 file using OpenJPEG executable
 * @param pFile jp2 file to load// w  ww  . jav a2s.c o  m
 * @return decoded buffered image from file
 */
private static BufferedImage loadJP2_Executable(File pFile) {
    logger.trace("executable decoder: " + pFile.getAbsolutePath());
    File tempOutput = null;
    try {
        tempOutput = File.createTempFile("dissimilar_" + pFile.getName() + "_", ".tif");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //FIXME: null check?
    tempOutput.deleteOnExit();

    List<String> commandLine = new LinkedList<String>();
    commandLine.add(OPENJPEGEXE.getAbsolutePath());
    commandLine.add("-i");
    commandLine.add(pFile.getAbsolutePath());
    commandLine.add("-o");
    commandLine.add(tempOutput.getAbsolutePath());

    logger.trace("running: " + commandLine.toString());

    ToolRunner runner = new ToolRunner(true);
    int exitCode = 0;
    try {
        exitCode = runner.runCommand(commandLine);
        logger.trace("exit code: " + exitCode);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (exitCode != 0) {
        //some error
        BufferedReader log = runner.getStdout();
        try {
            while (log.ready()) {
                logger.error("log: " + log.readLine());
            }
        } catch (IOException e) {

        }
    } else {
        try {
            BufferedImage image = Imaging.getBufferedImage(tempOutput);
            //force a delete
            tempOutput.delete();
            return image;
        } catch (ImageReadException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return null;
}