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:com.deployd.Deployd.java

public static JSONObject put(JSONObject input, String uri)
        throws ClientProtocolException, IOException, JSONException {

    HttpPut post = new HttpPut(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    post.setEntity(new ByteArrayEntity(input.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}

From source file:org.spring.data.gemfire.app.boot.SpringBootDataGemFireCacheClientApplication.java

@Override
public void run(String... args) throws Exception {
    Scanner scanner = new Scanner(System.in);
    scanner.next();// w w w  .j  ava 2 s  .  c o m
}

From source file:edu.cmu.cs.lti.ark.fn.utils.LemmatizeStuff.java

private static void run() throws FileNotFoundException {
    Scanner sc = new Scanner(new FileInputStream(infilename));
    PrintStream ps = new PrintStream(new FileOutputStream(outfilename));
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        ps.print(line + "\t");
        String[] toks = line.trim().split("\\s");
        int sentLen = Integer.parseInt(toks[0]);
        for (int i = 0; i < sentLen; i++) {
            String lemma = lemmatizer.getLemma(toks[i + 1].toLowerCase(), toks[i + 1 + sentLen]);
            ps.print(lemma + "\t");
        }// www . ja  v  a  2s.c om
        ps.println();
    }
    sc.close();
    closeQuietly(ps);
}

From source file:me.mast3rplan.phantombot.HTTPResponse.java

HTTPResponse(String address, String request) throws IOException {

    Socket sock = new Socket(address, 80);
    Writer output = new StringWriter();
    IOUtils.write(request, sock.getOutputStream(), "utf-8");
    IOUtils.copy(sock.getInputStream(), output);
    com.gmt2001.Console.out.println(output.toString());
    Scanner scan = new Scanner(sock.getInputStream());
    String errorLine = scan.nextLine();
    for (String line = scan.nextLine(); !line.equals(""); line = scan.nextLine()) {
        String[] keyval = line.split(":", 2);
        if (keyval.length == 2) {
            values.put(keyval[0], keyval[1].trim());
        } else {//from w  w  w  . ja  va2  s  .  c  o m
            //?
        }
    }
    while (scan.hasNextLine()) {
        body += scan.nextLine();
    }
    sock.close();

}

From source file:ml.shifu.core.util.CommonUtils.java

public static String[] loadHeader(InputStream is, String delimiter) {
    Set<String> nameSet = new HashSet<>();

    try (Scanner scanner = new Scanner(is)) {
        String headerLine = scanner.nextLine().trim();
        if (StringUtils.isEmpty(headerLine)) {
            throw new MalformedDataException("Header is empty");
        }//from ww w.j  av a  2  s.c  om
        LOG.info("Delimiter: " + delimiter);
        String[] header = StringUtils.splitPreserveAllTokens(headerLine, delimiter);

        LOG.info("Number of Fields: " + header.length);
        LOG.info(Arrays.toString(header));

        for (int i = 0; i < header.length; i++) {
            header[i] = header[i].trim();

            if (StringUtils.isEmpty(header[i])) {
                throw new MalformedDataException("Field is empty: #" + i + ", " + headerLine);
            }

            if (nameSet.contains(header[i])) {
                throw new MalformedDataException("Duplicated field names: " + header[i]);
            }
            nameSet.add(header[i]);
        }
        return header;
    }
}

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

@SuppressWarnings("resource")
@Override/*from  w  ww . j a va 2 s  .c om*/
protected void createOutputFiles(final String tempOutputDirectory, final File fastFile) throws IOException {
    useCustomSequenceLineSize = false;
    super.createOutputFiles(tempOutputDirectory, fastFile);

    tandemFile = new Scanner(getFile(tempOutputDirectory, TANDEM_REPEAT_FILE)).useDelimiter("\\" + PIPE);
}

From source file:divconq.tool.Updater.java

static public boolean tryUpdate() {
    @SuppressWarnings("resource")
    final Scanner scan = new Scanner(System.in);

    FuncResult<RecordStruct> ldres = Updater.loadDeployed();

    if (ldres.hasErrors()) {
        System.out.println("Error reading deployed.json file: " + ldres.getMessage());
        return false;
    }//w  ww  .j a v  a2 s.  c  om

    RecordStruct deployed = ldres.getResult();

    String ver = deployed.getFieldAsString("Version");
    String packfolder = deployed.getFieldAsString("PackageFolder");
    String packprefix = deployed.getFieldAsString("PackagePrefix");

    if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) {
        System.out.println("Error reading deployed.json file: Missing Version or PackageFolder");
        return false;
    }

    if (StringUtil.isEmpty(packprefix))
        packprefix = "DivConq";

    System.out.println("Current Version: " + ver);

    Path packpath = Paths.get(packfolder);

    if (!Files.exists(packpath) || !Files.isDirectory(packpath)) {
        System.out.println("Error reading PackageFolder - it may not exist or is not a folder.");
        return false;
    }

    File pp = packpath.toFile();
    RecordStruct deployment = null;
    File matchpack = null;

    for (File f : pp.listFiles()) {
        if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip"))
            continue;

        System.out.println("Checking: " + f.getName());

        // if not a match before, clear this
        deployment = null;

        try {
            ZipFile zf = new ZipFile(f);

            Enumeration<ZipArchiveEntry> entries = zf.getEntries();

            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();

                if (entry.getName().equals("deployment.json")) {
                    //System.out.println("crc: " + entry.getCrc());

                    FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry));

                    if (pres.hasErrors()) {
                        System.out.println("Error reading deployment.json file");
                        break;
                    }

                    deployment = (RecordStruct) pres.getResult();

                    break;
                }
            }

            zf.close();
        } catch (IOException x) {
            System.out.println("Error reading deployment.json file: " + x);
        }

        if (deployment != null) {
            String fndver = deployment.getFieldAsString("Version");
            String fnddependson = deployment.getFieldAsString("DependsOn");

            if (ver.equals(fnddependson)) {
                System.out.println("Found update: " + fndver);
                matchpack = f;
                break;
            }
        }
    }

    if ((matchpack == null) || (deployment == null)) {
        System.out.println("No updates found!");
        return false;
    }

    String fndver = deployment.getFieldAsString("Version");
    String umsg = deployment.getFieldAsString("UpdateMessage");

    if (StringUtil.isNotEmpty(umsg)) {
        System.out.println("========================================================================");
        System.out.println(umsg);
        System.out.println("========================================================================");
    }

    System.out.println();
    System.out.println("Do you want to install?  (y/n)");
    System.out.println();

    String p = scan.nextLine().toLowerCase();

    if (!p.equals("y"))
        return false;

    System.out.println();

    System.out.println("Intalling: " + fndver);

    Set<String> ignorepaths = new HashSet<>();

    ListStruct iplist = deployment.getFieldAsList("IgnorePaths");

    if (iplist != null) {
        for (Struct df : iplist.getItems())
            ignorepaths.add(df.toString());
    }

    ListStruct dflist = deployment.getFieldAsList("DeleteFiles");

    // deleting
    if (dflist != null) {
        for (Struct df : dflist.getItems()) {
            Path delpath = Paths.get(".", df.toString());

            if (Files.exists(delpath)) {
                System.out.println("Deleting: " + delpath.toAbsolutePath());

                try {
                    Files.delete(delpath);
                } catch (IOException x) {
                    System.out.println("Unable to Delete: " + x);
                }
            }
        }
    }

    // copying updates

    System.out.println("Checking for updated files: ");

    try {
        @SuppressWarnings("resource")
        ZipFile zf = new ZipFile(matchpack);

        Enumeration<ZipArchiveEntry> entries = zf.getEntries();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String entryname = entry.getName().replace('\\', '/');
            boolean xfnd = false;

            for (String exculde : ignorepaths)
                if (entryname.startsWith(exculde)) {
                    xfnd = true;
                    break;
                }

            if (xfnd)
                continue;

            System.out.print(".");

            Path localpath = Paths.get(".", entryname);

            if (entry.isDirectory()) {
                if (!Files.exists(localpath))
                    Files.createDirectories(localpath);
            } else {
                boolean hashmatch = false;

                if (Files.exists(localpath)) {
                    String local = null;
                    String update = null;

                    try (InputStream lin = Files.newInputStream(localpath)) {
                        local = HashUtil.getMd5(lin);
                    }

                    try (InputStream uin = zf.getInputStream(entry)) {
                        update = HashUtil.getMd5(uin);
                    }

                    hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update)
                            && local.equals(update));
                }

                if (!hashmatch) {
                    System.out.print("[" + entryname + "]");

                    try (InputStream uin = zf.getInputStream(entry)) {
                        Files.createDirectories(localpath.getParent());

                        Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (Exception x) {
                        System.out.println("Error updating: " + entryname + " - " + x);
                        return false;
                    }
                }
            }
        }

        zf.close();
    } catch (IOException x) {
        System.out.println("Error reading update package: " + x);
    }

    // updating local config
    deployed.setField("Version", fndver);

    OperationResult svres = Updater.saveDeployed(deployed);

    if (svres.hasErrors()) {
        System.out.println("Intalled: " + fndver
                + " but could not update deployed.json.  Repair the file before continuing.\nError: "
                + svres.getMessage());
        return false;
    }

    System.out.println("Intalled: " + fndver);

    return true;
}

From source file:net.sf.jaceko.mock.util.FileReader.java

public String readFileContents(final String fileName) {
    final StringBuilder text = new StringBuilder();
    final String newLine = System.getProperty("line.separator");
    Scanner scanner = null;/*w w  w.java 2  s .  co m*/
    try {
        final InputStream resourceAsStream = FileReader.class.getClassLoader().getResourceAsStream(fileName);
        if (resourceAsStream == null) {
            LOG.error("File not found: " + fileName);
            return null;
        } else {
            LOG.info(fileName + " found in classpath");
        }
        scanner = new Scanner(resourceAsStream);
        while (scanner.hasNextLine()) {
            text.append(scanner.nextLine() + newLine);
        }
    } catch (final Exception e) {
        LOG.error("Problem reading file : " + fileName, e);
        return null;
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }

    return text.toString();
}

From source file:com.mythesis.userbehaviouranalysis.Utils.java

/**
 * a method that reads a txt file with the necessary parameters
 * @param input the file that includes the necessary parameters
 *//*from   ww w .  ja  v a2s.  c o m*/
public void readInput(File input) {
    FileInputStream inputStream = null;
    Scanner sc = null;
    wordvectors = new HashMap<>();
    crawlerOutputPaths = new HashMap<>();

    HashMap<String, String> wordvectorsPaths = new HashMap<>();
    try {
        inputStream = new FileInputStream(input);
        sc = new Scanner(inputStream);

        if (sc.hasNextLine()) {
            int numProfiles = Integer.parseInt(sc.nextLine().split(";")[1].trim().toLowerCase());

            int j = 0;
            while (j < numProfiles) {
                String profile = "";
                if (sc.hasNextLine()) {
                    profile = sc.nextLine().split(";")[1].trim();
                }
                if (sc.hasNextLine()) {
                    String path = sc.nextLine().split(";")[1].trim();
                    crawlerOutputPaths.put(profile, path);
                }
                if (sc.hasNextLine()) {
                    String path = sc.nextLine().split(";")[1].trim();
                    wordvectorsPaths.put(profile, path);
                }
                j++;
            }
        }

        for (String profile : wordvectorsPaths.keySet()) {
            File file = new File(wordvectorsPaths.get(profile));
            try {
                List<String> wordvector = FileUtils.readLines(file);
                wordvectors.put(profile, (ArrayList<String>) wordvector);
            } catch (IOException ex) {
                Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (sc != null) {
            sc.close();
        }
    }

}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.IssueScanner.java

/**
 * Scan a file containing emails from gforge. Simply reads the file line by line and allows us to parse each line
 * for specific values we're interested in importing into Jira.
 *
 * @param theIssueFile the file we want to scan
 * @throws IOException thrown when the file is not found, or we could not write a file out when done.
 *///from w  w w.  j a  v a 2s.  co  m
public void scanFile(final File theIssueFile) throws IOException {
    try {
        fileScanner = new Scanner(theIssueFile);
        while (fileScanner.hasNextLine()) {
            processTheLine(fileScanner.nextLine());
        }
    } finally {
        if (issueList.size() > 0) {
            writeCommaDelimitedFile();
        }
        fileScanner.close();
    }
}