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) 

Source Link

Document

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

Usage

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnJavaFieldCutter.java

public void subsetFile(InputStream in, String outfile, Set<Integer> columns, Long numCases, String delimiter) {
    try {/*from ww  w  .  j a  va  2 s . co  m*/
        Scanner scanner = new Scanner(in);

        dbgLog.fine("outfile=" + outfile);

        BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
        scanner.useDelimiter("\\n");

        for (long caseIndex = 0; caseIndex < numCases; caseIndex++) {
            if (scanner.hasNext()) {
                String[] line = (scanner.next()).split(delimiter, -1);
                List<String> ln = new ArrayList<String>();
                for (Integer i : columns) {
                    ln.add(line[i]);
                }
                out.write(StringUtils.join(ln, "\t") + "\n");
            } else {
                throw new RuntimeException("Tab file has fewer rows than the determined number of cases.");
            }
        }

        while (scanner.hasNext()) {
            if (!"".equals(scanner.next())) {
                throw new RuntimeException(
                        "Tab file has extra nonempty rows than the determined number of cases.");

            }
        }

        scanner.close();
        out.close();

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

}

From source file:ncbi2rkb.NCBIExtractor.java

public int loadDivision(String fileName) {
    int nbDivision = 0;

    Path path = Paths.get(fileName);
    try (Scanner scanner = new Scanner(path)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] params = line.split("[|]");

            nbDivision++;//from  ww  w.  j a  va 2  s.c om

            int id = Integer.parseInt(params[0].trim());
            Division d = new Division(id, params[2].trim());
            this.divisions.put(id, d);
        }
    } catch (IOException ex) {
        System.out.println("Error during reading division file!");
        System.exit(0);
    }
    return nbDivision;
}

From source file:br.com.intelidev.dao.userDao.java

/**
  * Run the web service request/*from  w  w  w.j a v a2s . c o m*/
  * @param username
  * @param password
  * @return 
  */
public boolean login_acess(String username, String password) {
    HttpsURLConnection conn = null;
    boolean bo_return = false;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL("https://devicecloud.digi.com/ws/sci");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        //String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        //responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        //System.out.println(responseContent);
        bo_return = true;
    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.userDao.login_acess() Error: " + e);
        bo_return = false;
        //e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (bo_return) {
            System.out.println("Conectou ");
        } else {
            System.out.println("No conectou ");
        }

    }
    return bo_return;
}

From source file:edu.rit.flick.genetics.FastqFileInflator.java

@Override
protected void createOutputFiles(final String tempOutputDirectory, final File fastFile) throws IOException {
    super.createOutputFiles(tempOutputDirectory, fastFile);

    lengthfile = new BufferedInputStream(
            new FileInputStream(getFile(tempOutputDirectory, SEQUENCE_LENGTH_FILE)), DEFAULT_BUFFER) {
        @Override/*from ww w  .  j a  v  a  2 s  . c o m*/
        public synchronized int read() throws IOException {
            return super.read() << 8 | super.read() & 0x00ff;
        }
    };
    commentsfile = new Scanner(getFile(tempOutputDirectory, COMMENTS_FILE));

    final FileInputStream scoreFis = new FileInputStream(getFile(tempOutputDirectory, SEQUENCE_SCORE_FILE));
    scorefile = ByteBufferInputStream.map(scoreFis.getChannel());

    scoreFis.close();
}

From source file:eu.alpinweiss.filegen.util.generator.impl.SequenceGenerator.java

public SequenceGenerator(FieldDefinition fieldDefinition) {
    this.fieldDefinition = fieldDefinition;
    final String pattern = this.fieldDefinition.getPattern();
    if (!pattern.isEmpty() && pattern.matches(SEQUENCE_WITH_SUFFIX_AND_PREFIX)) {
        sequencePattern = cropPattern(pattern);

        try (Scanner scanner = new Scanner(sequencePattern[1])) {
            scanner.useDelimiter("\\D+");
            startNum = scanner.nextInt();
            digitCount = scanner.nextInt();
        }//from ww  w.  j ava 2s . co  m
        maxValue = Integer.parseInt(StringUtils.repeat("9", digitCount));
        shouldFail = sequencePattern[1].contains("FAIL");
    }
}

From source file:com.joliciel.talismane.machineLearning.TextFileWordList.java

public TextFileWordList(File file) {
    try {/*from  www . j av a 2s . c  om*/
        this.name = file.getName();

        Scanner scanner = new Scanner(
                new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")));
        int i = 1;
        String firstLine = scanner.nextLine();
        if (!firstLine.equals("Type: WordList")) {
            throw new JolicielException("A word list file must start with \"Type: WordList\"");
        }
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.length() > 0 && !line.startsWith("#")) {
                if (line.startsWith("Name: ")) {
                    this.name = line.substring("Name: ".length());
                    i++;
                    continue;
                }
                wordList.add(line);
            }
            i++;
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:br.com.intelidev.dao.DadosDao.java

public List<Dados> get_stream_data(String stream_api, String user, String pass) {

    HttpsURLConnection conn = null;
    List<Dados> list_return = new ArrayList<>();
    int i;//www.  j a  v  a2 s . c  o m

    try {
        // Create url to the Device Cloud server for a given web service request
        //00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1
        ObjectMapper mapper = new ObjectMapper();
        URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/" + stream_api);
        //URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = user + ":" + pass;
        System.out.println(userpassword);

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        System.out.println(responseContent);
        // Convert JSON string to Object
        StreamDados stream = mapper.readValue(responseContent, StreamDados.class);
        //System.out.println(stream.getList());
        System.out.println(stream.getList().size());
        for (i = 0; i < stream.getList().size(); i++) {
            list_return.add(stream.getList().get(i));
            //System.out.println("ts: "+ stream.getList().get(i).getTimestamp() + "Value: " + stream.getList().get(i).getValue());

        }

    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.DadosDao.get_stream_data() e" + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }

    return list_return;
}

From source file:io.github.seanboyy.lotReset.json.ReadJSON.java

/**Read JSON file by using configuration file's JSON value,
 * which points to the file/*from   w  w  w  .j  a  va 2  s  .  com*/
 * @param configLocation String which specifies the location of the config.properties file
 * @return <code>ArrayList&ltArrayList&ltLot&gt&gt lots</code> if no errors are encountered
 * @since 1.0 - Implemented config.properties in 2.0
 */
public static ArrayList<ArrayList<Lot>> read(String configLocation) {
    JSONParser parser = new JSONParser();
    URL url;
    File f;
    //lots is multidimensional in this format: {{fromLot,toLot},{fromLot,toLot},{fromLot,toLot},etc...}
    ArrayList<ArrayList<Lot>> lots = new ArrayList<ArrayList<Lot>>();
    Config config = ReadConfig.read(configLocation);
    final String[] alphabet = config.getAlpha();
    final String[] types = config.getType();
    final String[] worlds = config.getWorld();
    try {
        url = new URL(config.getJSON());
        InputStream in = url.openStream();
        f = File.createTempFile("temp", "json");
        FileWriter file = new FileWriter(f);
        Scanner input = new Scanner(in);
        while (input.hasNextLine()) {
            file.write(input.nextLine());
        }
        input.close();
        file.close();
        Object obj = parser.parse(new FileReader(f));
        JSONObject jsonObj = (JSONObject) obj;
        JSONObject regions = (JSONObject) jsonObj.get("Regions");
        for (String a : worlds) {
            for (String b : types) {
                for (String c : alphabet) {
                    for (int d = 1; d <= alphabet.length; ++d) {
                        String lotId = a + "-" + b + "-" + c + d;
                        String lotIdA = a + "_" + b + "-" + c + d;
                        String lotIdB = a + "-" + b + "_" + c + d;
                        String lotIdC = a + "_" + b + "_" + c + d;
                        JSONObject lot = (JSONObject) regions.get(lotId);
                        JSONObject lotA = (JSONObject) regions.get(lotIdA);
                        JSONObject lotB = (JSONObject) regions.get(lotIdB);
                        JSONObject lotC = (JSONObject) regions.get(lotIdC);
                        ArrayList<Lot> lotInfo = new ArrayList<Lot>();
                        if (lot != null) {
                            lotInfo.add(new Lot((long) lot.get("source_minX"), (long) lot.get("source_maxX"),
                                    (long) lot.get("source_minY"), (long) lot.get("source_maxY"),
                                    (long) lot.get("source_minZ"), (long) lot.get("source_maxZ"),
                                    (String) lot.get("source_file"), lotId));
                            lotInfo.add(new Lot((long) lot.get("dest_minX"), (long) lot.get("dest_maxX"),
                                    (long) lot.get("dest_minY"), (long) lot.get("dest_maxY"),
                                    (long) lot.get("dest_minZ"), (long) lot.get("dest_maxZ"),
                                    (String) lot.get("dest_file"), lotId));
                            lots.add(lotInfo);
                        }
                        if (lotA != null) {
                            lotInfo.add(new Lot((long) lotA.get("source_minX"), (long) lotA.get("source_maxX"),
                                    (long) lotA.get("source_minY"), (long) lotA.get("source_maxY"),
                                    (long) lotA.get("source_minZ"), (long) lotA.get("source_maxZ"),
                                    (String) lotA.get("source_file"), lotIdA));
                            lotInfo.add(new Lot((long) lotA.get("dest_minX"), (long) lotA.get("dest_maxX"),
                                    (long) lotA.get("dest_minY"), (long) lotA.get("dest_maxY"),
                                    (long) lotA.get("dest_minZ"), (long) lotA.get("dest_maxZ"),
                                    (String) lotA.get("dest_file"), lotIdA));
                            lots.add(lotInfo);
                        }
                        if (lotB != null) {
                            lotInfo.add(new Lot((long) lotB.get("source_minX"), (long) lotB.get("source_maxX"),
                                    (long) lotB.get("source_minY"), (long) lotB.get("source_maxY"),
                                    (long) lotB.get("source_minZ"), (long) lotB.get("source_maxZ"),
                                    (String) lotB.get("source_file"), lotIdB));
                            lotInfo.add(new Lot((long) lotB.get("dest_minX"), (long) lotB.get("dest_maxX"),
                                    (long) lotB.get("dest_minY"), (long) lotB.get("dest_maxY"),
                                    (long) lotB.get("dest_minZ"), (long) lotB.get("dest_maxZ"),
                                    (String) lotB.get("dest_file"), lotIdB));
                            lots.add(lotInfo);
                        }
                        if (lotC != null) {
                            lotInfo.add(new Lot((long) lotC.get("source_minX"), (long) lotC.get("source_maxX"),
                                    (long) lotC.get("source_minY"), (long) lotC.get("source_maxY"),
                                    (long) lotC.get("source_minZ"), (long) lotC.get("source_maxZ"),
                                    (String) lotC.get("source_file"), lotIdC));
                            lotInfo.add(new Lot((long) lotC.get("dest_minX"), (long) lotC.get("dest_maxX"),
                                    (long) lotC.get("dest_minY"), (long) lotC.get("dest_maxY"),
                                    (long) lotC.get("dest_minZ"), (long) lotC.get("dest_maxZ"),
                                    (String) lotC.get("dest_file"), lotIdC));
                            lots.add(lotInfo);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        System.out.println("FILE ERROR FROM READING JSON");
        e.printStackTrace();
        return null;
    } catch (ParseException e) {
        System.out.println("PARSER ERROR FROM READING JSON");
        e.printStackTrace();
        return null;
    }
    return lots;
}

From source file:cloudlens.engine.CLIterator.java

public static CLIterator source(BlockEngine engine, InputStream inputStream, boolean withHistory) {
    final BlockObject wrap = engine.eval("function(message) { return {message:message}; }");
    final CLIterator res = new CLIterator(engine, new Iterator<BlockObject>() {
        final Scanner scan = new Scanner(inputStream);

        @Override//from  w ww .j a va2  s . c  om
        protected void finalize() throws IOException {
            if (scan != null) {
                scan.close();
            }
        }

        @Override
        public boolean hasNext() {
            return scan.hasNext();
        }

        @Override
        public BlockObject next() {
            final BlockObject record = wrap.call(scan.nextLine());
            return record;
        }
    }, withHistory);
    if (withHistory) {
        res.iterate();
    }
    ;
    return res;
}

From source file:com.lidroid.xutils.http.client.URLEncodedUtils.java

/**
 * Returns a list of {@link org.apache.http.NameValuePair NameValuePairs} as built from the
 * URI's query portion. For example, a URI of
 * http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three
 * NameValuePairs, one for a=1, one for b=2, and one for c=3.
 * <p/>//from   ww w  .j a v  a2 s .  c  o  m
 * This is typically useful while parsing an HTTP PUT.
 *
 * @param uri      uri to parse
 * @param encoding encoding to use while parsing the query
 */
public static List<NameValuePair> parse(final URI uri, final String encoding) {
    final String query = uri.getRawQuery();
    if (query != null && query.length() > 0) {
        List<NameValuePair> result = new ArrayList<NameValuePair>();
        Scanner scanner = new Scanner(query);
        parse(result, scanner, encoding);
        return result;
    } else {
        return Collections.emptyList();
    }
}