Example usage for java.util Scanner Scanner

List of usage examples for java.util Scanner Scanner

Introduction

In this page you can find the example usage for java.util Scanner Scanner.

Prototype

public Scanner(ReadableByteChannel source, Charset charset) 

Source Link

Document

Constructs a new Scanner that produces values scanned from the specified channel.

Usage

From source file:cz.autoclient.github.json.GitHubJson.java

public static JSONObject fromURL(URL url) {
    Scanner s;//from www .j av  a2  s . co  m
    try {
        s = new Scanner(url.openStream(), "UTF-8");
    } catch (IOException ex) {
        throw new IllegalArgumentException("JSON file not found at " + url);
    }
    s.useDelimiter("\\A");
    if (s.hasNext()) {
        String out = s.next();
        try {
            return new JSONObject(out);
        } catch (JSONException ex) {
            throw new IllegalArgumentException(
                    "Invalid JSON contents at " + url + " - \n         JSON error:" + ex);
            //Logger.getLogger(DataLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else
        throw new IllegalArgumentException("JSON file not found at " + url);
}

From source file:Main.java

private static ArrayList<String> getMatches(InputStream in, Pattern pattern) {
    ArrayList<String> matches = new ArrayList<String>();
    Scanner scanner = new Scanner(in, "UTF-8");
    String match = "";
    while (match != null) {
        match = scanner.findWithinHorizon(pattern, 0);
        if (match != null) {
            matches.add(scanner.match().group(2));
        }/*w w  w  . j  av a  2s .  com*/
    }

    return matches;
}

From source file:Main.java

/**
 * read one file and return its content as string
 * @param fileName//from  ww w  .  j a  v  a  2 s. com
 * @return
 * @throws FileNotFoundException
 */
public static String readFileToString(String fileName) throws FileNotFoundException {
    File file = new File(fileName);
    if (file.exists()) {
        StringBuilder stringBuilder = new StringBuilder((int) file.length());
        Scanner scanner = new Scanner(file, "UTF-8");
        String lineSeparator = System.getProperty("line.separator");

        while (scanner.hasNextLine()) {
            stringBuilder.append(scanner.nextLine() + lineSeparator);
        }

        scanner.close();
        return stringBuilder.toString();
    }

    Log.e(TAG_CLASS, "no file called: " + fileName);
    return null;
}

From source file:br.univali.ps.fuzzy.portugolFuzzyCorretor.control.FileController.java

public static String formatarArquivoTexto(File file) throws FileNotFoundException {
    BufferedReader reader = new BufferedReader(new FileReader(file));
    StringBuilder text = new StringBuilder();
    String NL = System.getProperty("line.separator");
    Scanner scanner = new Scanner(file, "ISO-8859-1");
    while (scanner.hasNextLine()) {
        text.append(scanner.nextLine() + NL);
    }/*w w w.j av a2s.  c o m*/
    scanner.close();
    return text.toString();
}

From source file:org.gkh.racf.JSONUtil.java

public static JSONObject getJSONAsResource(String path) throws JSONException {
    InputStream in = JSONParserTemplateBuilder.class.getResourceAsStream(path);

    Scanner scanner = new Scanner(in, "UTF-8");
    String json = scanner.useDelimiter("\\A").next();
    scanner.close();//from   www. j  a  va  2 s . c o m

    if (isValidJSON(json)) {
        return new JSONObject(json);
    }

    return null;
}

From source file:com.msopentech.thali.utilities.webviewbridge.BridgeManager.java

/**
 * A useful utility for small streams. The stream will be closed by this method.
 *
 * Taken from http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
 * @param inputStream//from  w  ww . j  a  v  a2 s . c  o  m
 * @return Stream as a string
 */
public static String turnUTF8InputStreamToString(InputStream inputStream) {
    try {
        Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:io.fabric8.che.starter.util.Reader.java

public String read(URL url) throws IOException {
    try (Scanner skanner = new Scanner(url.openStream(), "UTF-8")) {
        return skanner.useDelimiter("\\A").next();
    }/*  www  .j  a v  a 2 s.  c  om*/
}

From source file:eu.dasish.annotation.backend.dao.impl.JdbcResourceDaoTest.java

public static String getNormalisedSql() throws FileNotFoundException, URISyntaxException {
    // remove the unsupported sql for the test
    final URL sqlUrl = JdbcResourceDaoTest.class.getResource("/sql/DashishAnnotatorCreate.sql");
    String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
    for (String unknownToken : new String[] { "SET client_encoding", "CREATE DATABASE", "\\\\connect",
            "SET default_with_oids",
            //"ALTER SEQUENCE",
            //ALTER TABLE ONLY",
            //"ADD CONSTRAINT",
            //"CREATE INDEX", 
            // "ALTER TABLE ONLY [a-z]* ALTER COLUMN",
            // "ALTER TABLE ONLY [^A]* ADD CONSTRAINT"
    }) {/*www  .j av a2s  .  c o  m*/
        sqlString = sqlString.replaceAll(unknownToken, "-- " + unknownToken);
    }

    sqlString = sqlString.replaceAll("bytea", "blob");
    sqlString = sqlString.replaceAll("SERIAL NOT NULL", "INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
    sqlString = sqlString.replaceAll("\\(current_timestamp AT TIME ZONE 'UTC'\\)",
            "current_timestamp AT TIME ZONE INTERVAL '00:00' HOUR TO MINUTE");
    return sqlString;
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http(String s) throws SQLException, IOException {

    String resp = "";
    final URL url = new URL(s);
    final URLConnection connection = url.openConnection();
    connection.setConnectTimeout(60000);
    connection.setReadTimeout(60000);/*from   ww  w  .jav  a2 s . co m*/
    connection.addRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
    connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
    while (reader.hasNextLine()) {
        final String line = reader.nextLine();
        resp += line + "\n";
    }
    reader.close();

    return resp;
}

From source file:com.networknt.light.server.handler.loader.MenuLoader.java

private static void loadMenuFile(File file) {
    Scanner scan = null;//from   w w  w . j  a va  2  s .c  o m
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion. convert to map
        String content = scan.useDelimiter("\\Z").next();
        HttpPost httpPost = new HttpPost("http://injector:8080/api/rs");
        StringEntity input = new StringEntity(content);
        input.setContentType("application/json");
        httpPost.setEntity(input);
        CloseableHttpResponse response = httpclient.execute(httpPost);

        try {
            System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
            String json = "";
            String line = "";
            while ((line = rd.readLine()) != null) {
                json = json + line;
            }
            System.out.println("json = " + json);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}