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:azureml_besapp.AzureML_BESApp.java

/**
 * Read the JSON schema from the file rrsJson.json
 * //from  w ww .  j a  v  a  2  s  .c  o  m
 * @param filename It expects a fully qualified file name that contains input JSON file
 */
public static void readJson(String filename) {
    try {
        File apiFile = new File(filename);
        Scanner sc = new Scanner(apiFile);
        jsonBody = "";
        while (sc.hasNext()) {
            jsonBody += sc.nextLine() + "\n";
        }
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

From source file:adviewer.util.JSONIO.java

/**
 * Take in file and return one string of json data
 * //  www  .  ja v a 2s  . c om
 * @return
 * @throws IOException
 */
public static String readJSONFile(File inFile) {
    String readFile = "";

    try {
        File fileIn = inFile;

        //if the file is not there then create the file
        if (fileIn.createNewFile()) {
            System.out.println(fileIn + " was created ");
        }

        FileReader fr = new FileReader(fileIn);
        Scanner sc = new Scanner(fr);

        while (sc.hasNext()) {
            readFile += sc.nextLine().trim();
        }

        return readFile;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // System.out.println( readFile  );
    return readFile;
}

From source file:de.prozesskraft.ptest.Fingerprint.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try// ww w  .j a va 2s  . co  m
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Fingerprint.class) + "/" + "../etc/ptest-fingerprint.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option opath = OptionBuilder.withArgName("PATH").hasArg()
            .withDescription(
                    "[mandatory; default: .] the root path for the tree you want to make a fingerprint from.")
            //            .isRequired()
            .create("path");

    Option osizetol = OptionBuilder.withArgName("FLOAT").hasArg().withDescription(
            "[optional; default: 0.02] the sizeTolerance (as factor in percent) of all file entries will be set to this value. [0.0 < sizetol < 1.0]")
            //            .isRequired()
            .create("sizetol");

    Option omd5 = OptionBuilder.withArgName("no|yes").hasArg()
            .withDescription("[optional; default: yes] should be the md5sum of files determined? no|yes")
            //            .isRequired()
            .create("md5");

    Option oignore = OptionBuilder.withArgName("STRING").hasArgs()
            .withDescription("[optional] path-pattern that should be ignored when creating the fingerprint")
            //            .isRequired()
            .create("ignore");

    Option oignorefile = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[optional] file with path-patterns (one per line) that should be ignored when creating the fingerprint")
            //            .isRequired()
            .create("ignorefile");

    Option ooutput = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory; default: <path>/fingerprint.xml] fingerprint file")
            //            .isRequired()
            .create("output");

    Option of = new Option("f", "[optional] force overwrite fingerprint file if it already exists");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(opath);
    options.addOption(osizetol);
    options.addOption(omd5);
    options.addOption(oignore);
    options.addOption(oignorefile);
    options.addOption(ooutput);
    options.addOption(of);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);

    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingerprint", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     " + web);
        System.out.println("author: " + author);
        System.out.println("version:" + version);
        System.out.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    String path = "";
    String sizetol = "";
    boolean md5 = false;
    Float sizetolFloat = null;
    String output = "";
    java.io.File ignorefile = null;
    ArrayList<String> ignore = new ArrayList<String>();

    if (!(commandline.hasOption("path"))) {
        System.err.println("setting default for -path=.");
        path = ".";
    } else {
        path = commandline.getOptionValue("path");
    }

    if (!(commandline.hasOption("sizetol"))) {
        System.err.println("setting default for -sizetol=0.02");
        sizetol = "0.02";
        sizetolFloat = 0.02F;
    } else {
        sizetol = commandline.getOptionValue("sizetol");
        sizetolFloat = Float.parseFloat(sizetol);

        if ((sizetolFloat > 1) || (sizetolFloat < 0)) {
            System.err.println("use only values >=0.0 and <1.0 for -sizetol");
            System.exit(1);
        }
    }

    if (!(commandline.hasOption("md5"))) {
        System.err.println("setting default for -md5=yes");
        md5 = true;
    } else if (commandline.getOptionValue("md5").equals("no")) {
        md5 = false;
    } else if (commandline.getOptionValue("md5").equals("yes")) {
        md5 = true;
    } else {
        System.err.println("use only values no|yes for -md5");
        System.exit(1);
    }

    if (commandline.hasOption("ignore")) {
        ignore.addAll(Arrays.asList(commandline.getOptionValues("ignore")));
    }

    if (commandline.hasOption("ignorefile")) {
        ignorefile = new java.io.File(commandline.getOptionValue("ignorefile"));
        if (!ignorefile.exists()) {
            System.err.println("warn: ignore file does not exist: " + ignorefile.getCanonicalPath());
        }
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("setting default for -output=" + path + "/fingerprint.xml");
        output = path + "/fingerprint.xml";
    } else {
        output = commandline.getOptionValue("output");
    }

    // wenn output bereits existiert -> abbruch
    java.io.File outputFile = new File(output);
    if (outputFile.exists()) {
        if (commandline.hasOption("f")) {
            outputFile.delete();
        } else {
            System.err
                    .println("error: output file (" + output + ") already exists. use -f to force overwrite.");
            System.exit(1);
        }
    }

    //      if ( !( commandline.hasOption("output")) )
    //      {
    //         System.err.println("option -output is mandatory.");
    //         exiter();
    //      }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Dir dir = new Dir();
    dir.setBasepath(path);
    dir.setOutfilexml(output);

    // ignore file in ein Array lesen
    if ((ignorefile != null) && (ignorefile.exists())) {
        Scanner sc = new Scanner(ignorefile);
        while (sc.hasNextLine()) {
            ignore.add(sc.nextLine());
        }
        sc.close();
    }

    //      // autoignore hinzufuegen
    //      String autoIgnoreString = ini.get("autoignore", "autoignore");
    //      ignoreLines.addAll(Arrays.asList(autoIgnoreString.split(",")));

    //      // debug
    //      System.out.println("ignorefile content:");
    //      for(String actLine : ignore)
    //      {
    //         System.out.println("line: "+actLine);
    //      }

    try {
        dir.genFingerprint(sizetolFloat, md5, ignore);
    } catch (NullPointerException e) {
        System.err.println("file/dir does not exist " + path);
        e.printStackTrace();
        exiter();
    } catch (IOException e) {
        e.printStackTrace();
        exiter();
    }

    System.out.println("writing to file: " + dir.getOutfilexml());
    dir.writeXml();

}

From source file:msuresh.raftdistdb.RaftClient.java

public static void SetValue(String name, String key, String value) throws FileNotFoundException {
    if (key == null || key.isEmpty()) {
        return;/*w  ww .j  a  v a2  s.  c  o  m*/
    }
    File configFile = new File(Constants.STATE_LOCATION + name + ".info");
    if (!configFile.exists() || configFile.isDirectory()) {
        FileNotFoundException ex = new FileNotFoundException();
        throw ex;
    }
    try {
        System.out.println("Adding key .. hold on..");
        String content = new Scanner(configFile).useDelimiter("\\Z").next();
        JSONObject config = (JSONObject) (new JSONParser()).parse(content);
        Long numPart = (Long) config.get("countPartitions");
        Integer shardId = key.hashCode() % numPart.intValue();
        JSONArray memberJson = (JSONArray) config.get(shardId.toString());
        List<Address> members = new ArrayList<>();
        for (int i = 0; i < memberJson.size(); i++) {
            JSONObject obj = (JSONObject) memberJson.get(i);
            Long port = (Long) obj.get("port");
            String address = (String) obj.get("address");
            members.add(new Address(address, port.intValue()));
        }
        CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build();
        client.open().join();
        client.submit(new PutCommand(key, value)).get();
        client.close().join();
        while (client.isOpen()) {
            Thread.sleep(1000);
        }
        System.out.println("key " + key + " with value : " + value + " has been added to the cluster");
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}

From source file:com.thoughtworks.go.util.OperatingSystem.java

private static String detectCompleteName() {
    String[] command = { "python", "-c", "import platform;print(platform.linux_distribution())" };
    try {//from   ww w .  j a  v  a  2 s  .  co  m
        Process process = Runtime.getRuntime().exec(command);
        Scanner scanner = new Scanner(process.getInputStream());
        String line = scanner.nextLine();
        OS_COMPLETE_NAME = cleanUpPythonOutput(line);
    } catch (Exception e) {
        try {
            OS_COMPLETE_NAME = readFromOsRelease();
        } catch (Exception ignored) {
            OS_COMPLETE_NAME = OS_FAMILY_NAME;
        }
    }
    return OS_COMPLETE_NAME;
}

From source file:Main.java

/**
 * Remove indexes from an xpath string./*from w  w  w  .j  a va2 s  . c  o m*/
 * @param xpath xpath string
 * @return unindexed xpath string
 */
public static String removeIndexes(String xpath) {
    final String[] partialSteps = xpath.split("[/]");
    if (partialSteps.length == 0) {
        return xpath;
    }

    int startIndex = 0;
    StringBuffer buf = new StringBuffer();

    for (int i = startIndex; i < partialSteps.length; i++) {
        String step = partialSteps[i];
        int start = step.indexOf('[');

        if (start > -1) {
            int end = step.indexOf(']');
            Scanner scanner = new Scanner(step.substring(start + 1, end));
            if (scanner.hasNextInt()) {
                // remove index and the brackets
                step = step.substring(0, start);
            }
        }
        buf.append(step);
        if (i < partialSteps.length - 1) {
            buf.append("/");
        }
    }
    return buf.toString();
}

From source file:game.utils.Utils.java

public static String readFile(File file) {
    String ret = null;/*w  w  w  .  ja  va2s .  co m*/
    try {
        Scanner scanner = new Scanner(file);
        ret = scanner.useDelimiter("\\Z").next();
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:de.ifgi.mosia.wpswfs.Util.java

public static Set<String> readConfigFilePerLine(String resourcePath) throws IOException {
    URL resURL = Util.class.getResource(resourcePath);
    URLConnection resConn = resURL.openConnection();
    resConn.setUseCaches(false);//from  w  w w .  ja  va  2 s. c o  m
    InputStream contents = resConn.getInputStream();

    Scanner sc = new Scanner(contents);
    Set<String> result = new HashSet<String>();
    String line;
    while (sc.hasNext()) {
        line = sc.nextLine();
        if (line != null && !line.isEmpty() && !line.startsWith("#")) {
            result.add(line.trim());
        }
    }
    sc.close();

    return result;
}

From source file:medcheck.Medcheck.java

private static String getJSONString(File jsonFile) {
    String jsonString = "";
    try {/* w ww.j av  a2s.  c  o m*/
        Scanner fileScanner = new Scanner(jsonFile);
        boolean isFirstLine = true;
        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine().trim();
            if (!isFirstLine) {
                jsonString += " ";
            }
            isFirstLine = false;
            jsonString += line;
        }
    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
        e.printStackTrace();
        exit(1);
    }

    return jsonString;
}

From source file:com.richard.memorystore.tcp.TcpServer.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/* w w w  .  ja v a 2 s .  c  om*/
 */
public static void main() {

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration                    "
            + "\n          TCP-Client-Server Sample!                      "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springintegration.org/                    "
            + "\n                                                         "
            + "\n=========================================================");

    final GenericXmlApplicationContext context = TcpServer.setupContext();
    final SimpleGateway gateway = context.getBean(SimpleGateway.class);
    final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);

    System.out.print("Waiting for server to accept connections...");
    TestingUtilities.waitListening(crLfServer, 10000L);
    System.out.println("running.\n\n");

    System.out.println("Please enter some text and press <enter>: ");
    System.out.println("\tNote:");
    System.out.println("\t- Entering FAIL will create an exception");
    System.out.println("\t- Entering q will quit the application");
    System.out.print("\n");
    System.out.println("\t--> Please also check out the other samples, " + "that are provided as JUnit tests.");
    System.out.println("\t--> You can also connect to the server on port '" + crLfServer.getPort()
            + "' using Telnet.\n\n");

    InputProcessor lineProcessor = new InputProcessor();

    while (true) {

        final String input = scanner.nextLine();

        System.out.println("GOT THIS!!!" + input);

        KeyValueController keyValueController = new KeyValueController();

        KeyValue keyValue = lineProcessor.processLine(input);

        keyValueController.addToMemoryStore(keyValue.getKey(), keyValue.getValue());

        if ("q".equals(input.trim())) {
            break;
        } else {
            final String result = gateway.send(input);
            System.out.println(result);
        }
    }

    System.out.println("Exiting application...bye.");
    System.exit(0);

}