Example usage for java.util Scanner close

List of usage examples for java.util Scanner close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes this scanner.

Usage

From source file:css.variable.converter.CSSVariableConverter.java

/**
 * Go through existing CSS Files and replace variable access with variable
 * values//  w  w  w.j  a  v  a  2s.co  m
 *
 * @param rootCSSVars All css variables you want to convert from name to value
 */
private static void editForRelease(ArrayList<CSSVar> rootCSSVars) {
    for (File cssFile : theCSSList) {

        ArrayList<CSSVar> localCSSVars = getCSSVars(cssFile, ":local");
        for (CSSVar cssVar : rootCSSVars) {
            if (!localCSSVars.contains(cssVar)) {
                localCSSVars.add((CSSVar) (cssVar.clone()));
            }
        }

        // This will store info the new text for the file we will write below
        ArrayList<String> filesNewInfo = new ArrayList<String>();
        try {

            Scanner fileReader = new Scanner(cssFile);
            while (fileReader.hasNextLine()) {

                String currentLine = fileReader.nextLine();

                // If we find variables, replace them, with their value
                if (currentLine.contains("var(")) {
                    for (CSSVar var : localCSSVars) {
                        while (currentLine.contains(var.getName())) {
                            currentLine = currentLine.replace("var(" + var.getName() + ")", var.getValue());
                        }
                    }
                }
                // Add new currentLine to be written
                filesNewInfo.add(currentLine);
            }
            fileReader.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CSSVariableConverter.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Write the new files below
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(cssFile.getPath()));

            while (!filesNewInfo.isEmpty()) {
                writer.write(filesNewInfo.get(0));
                writer.newLine();
                filesNewInfo.remove(0);
            }
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(CSSVariableConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.ibm.bi.dml.api.DMLScript.java

/**
 * // w  w w .j  av a2 s . com
 * @param argname
 * @param arg
 * @return
 * @throws IOException 
 * @throws LanguageException 
 */
protected static String readDMLScript(String argname, String script) throws IOException, LanguageException {
    boolean fromFile = argname.equals("-f") ? true : false;
    String dmlScriptStr = null;

    if (fromFile) {
        //read DML script from file
        if (script == null)
            throw new LanguageException("DML script path was not specified!");

        StringBuilder sb = new StringBuilder();
        BufferedReader in = null;
        try {
            //read from hdfs or gpfs file system
            if (script.startsWith("hdfs:") || script.startsWith("gpfs:")) {
                if (!LocalFileUtils.validateExternalFilename(script, true))
                    throw new LanguageException("Invalid (non-trustworthy) hdfs filename.");
                FileSystem fs = FileSystem.get(ConfigurationManager.getCachedJobConf());
                Path scriptPath = new Path(script);
                in = new BufferedReader(new InputStreamReader(fs.open(scriptPath)));
            }
            // from local file system
            else {
                if (!LocalFileUtils.validateExternalFilename(script, false))
                    throw new LanguageException("Invalid (non-trustworthy) local filename.");
                in = new BufferedReader(new FileReader(script));
            }

            //core script reading
            String tmp = null;
            while ((tmp = in.readLine()) != null) {
                sb.append(tmp);
                sb.append("\n");
            }
        } catch (IOException ex) {
            LOG.error("Failed to read the script from the file system", ex);
            throw ex;
        } finally {
            if (in != null)
                in.close();
        }

        dmlScriptStr = sb.toString();
    } else {
        //parse given script string 
        if (script == null)
            throw new LanguageException("DML script was not specified!");

        InputStream is = new ByteArrayInputStream(script.getBytes());
        Scanner scan = new Scanner(is);
        dmlScriptStr = scan.useDelimiter("\\A").next();
        scan.close();
    }

    return dmlScriptStr;
}

From source file:CommandLineInterpreter.java

/**
 *
 *
 * @param file//from w w  w  .  j ava2  s  . c  om
 * @param guiAlert
 * @return
 */
public static boolean checkResources(final File file, final boolean guiAlert) {
    Scanner input = null;
    String message = null;
    try {
        input = new Scanner(file);
        while (input.hasNextLine()) {
            String currentFilePath = input.nextLine().trim();
            if (!currentFilePath.isEmpty()) {
                File currentFile = new File(currentFilePath);
                if (!currentFile.exists() || !currentFile.canRead() || !currentFile.canWrite()) {
                    message = "Can not read/write resource file:\n\"" + currentFile.getAbsolutePath() + "\"";
                    alert(message, guiAlert);
                    return false;
                }
            }
        }
    } catch (Exception e) {
        // TODO: logging
        e.printStackTrace();
    } finally {
        if (input != null) {
            input.close();
        }
    }

    return true;
}

From source file:clummy.classes.DataHandlingClass.java

/**
 * to read file by line and pass each line to arraylist
 * only read starting at the third line//from  ww  w .ja  va 2 s  .c om
 * @param fileName String
 * @return ArrayList
 */
public static ArrayList<String> readFile(String fileName) {
    ArrayList<String> readList = new ArrayList<>();

    Scanner scan;
    try {
        scan = new Scanner(new FileReader(fileName));
        int lineCount = 0;
        while (scan.hasNextLine()) {
            lineCount++;
            if (lineCount <= 3)
                scan.nextLine();
            if (lineCount >= 4)
                readList.add(scan.nextLine());
        }
        scan.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
    }
    return readList;
}

From source file:instastats.InstaStats.java

private String getAccessCode() {
    String codePath = this.getClass().getResource("").getPath() + localCodePath;
    File codeFile = new File(codePath);
    String code = null;//  w  w w. j a v a2  s . com
    try {
        Scanner scanner = new Scanner(codeFile);
        code = scanner.next();
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return code;
}

From source file:ml.shifu.shifu.actor.NormalizeDataActorTest.java

@Test
public void testActor() throws IOException, InterruptedException {
    File tmpDir = new File("./tmp");
    if (tmpDir.isDirectory()) {
        FileUtils.deleteDirectory(tmpDir);
    }/*from  w w w .j ava  2  s . c  om*/

    FileUtils.forceMkdir(tmpDir);

    ActorRef normalizeRef = actorSystem.actorOf(new Props(new UntypedActorFactory() {
        private static final long serialVersionUID = 6777309320338075269L;

        public UntypedActor create() throws IOException {
            return new NormalizeDataActor(modelConfig, columnConfigList, new AkkaExecStatus(true));
        }
    }), "normalize-calculator");

    List<Scanner> scanners = ShifuFileUtils.getDataScanners(
            "src/test/resources/example/cancer-judgement/DataStore/DataSet1", SourceType.LOCAL);
    normalizeRef.tell(new AkkaActorInputMessage(scanners), normalizeRef);

    while (!normalizeRef.isTerminated()) {
        Thread.sleep(5000);
    }

    File outputFile = new File("./tmp/NormalizedData");
    Assert.assertTrue(outputFile.exists());

    for (Scanner scanner : scanners) {
        scanner.close();
    }
}

From source file:io.anserini.doc.GenerateRegressionDocsTest.java

@Test
public void main() throws Exception {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    URL resource = GenerateRegressionDocsTest.class.getResource("/regression/all.yaml");
    DataModel data = mapper.readValue(Paths.get(resource.toURI()).toFile(), DataModel.class);
    //System.out.println(ReflectionToStringBuilder.toString(data, ToStringStyle.MULTI_LINE_STYLE));

    for (String collection : data.getCollections().keySet()) {
        Map<String, String> valuesMap = new HashMap<>();
        valuesMap.put("index_cmds", data.generateIndexingCommand(collection));
        valuesMap.put("ranking_cmds", data.generateRankingCommand(collection));
        valuesMap.put("eval_cmds", data.generateEvalCommand(collection));
        valuesMap.put("effectiveness", data.generateEffectiveness(collection));
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        URL template = GenerateRegressionDocsTest.class
                .getResource(String.format("/docgen/templates/%s.template", collection));
        Scanner scanner = new Scanner(Paths.get(template.toURI()).toFile(), "UTF-8");
        String text = scanner.useDelimiter("\\A").next();
        scanner.close();
        String resolvedString = sub.replace(text);

        FileUtils.writeStringToFile(new File(String.format("docs/experiments-%s.md", collection)),
                resolvedString, "UTF-8");
    }/*from  w  w  w  .j  a va2  s  .  c o  m*/
}

From source file:org.zrgs.spring.statemachine.CommonConfiguration.java

@Bean
public String stateChartModel() throws IOException {
    ClassPathResource model = new ClassPathResource("statechartmodel.txt");
    InputStream inputStream = model.getInputStream();
    Scanner scanner = new Scanner(inputStream);
    String content = scanner.useDelimiter("\\Z").next();
    scanner.close();
    return content;
}

From source file:ml.shifu.shifu.fs.ShifuFileUtilsTest.java

@Test
public void getDataScannersTest() throws IOException {

    File file = new File("common-utils");
    if (file.exists()) {
        FileUtils.deleteDirectory(file);
    }//  ww  w  .j  av  a 2s . c  o  m
    FileUtils.forceMkdir(file);

    List<Scanner> list = ShifuFileUtils.getDataScanners(Arrays.asList(new String[] { "common-utils" }),
            SourceType.HDFS);

    Assert.assertTrue(list.size() == 0);

    file = new File("common-utils/part-0000");
    FileUtils.touch(file);

    list = ShifuFileUtils.getDataScanners(Arrays.asList(new String[] { "common-utils" }), SourceType.HDFS);

    Assert.assertTrue(list.size() == 1);

    for (Scanner scanner : list) {
        scanner.close();
    }

    FileUtils.deleteDirectory(new File("common-utils"));
}

From source file:DataSci.main.JsonRequestResponseController.java

/**
 * Read the API key and API URL of Azure ML request response REST API
 * /*from w w w  .  j  a  v a  2  s.c o m*/
 * @param filename fully qualified file name that contains API key and API URL
 */
public void readApiInfo(String filename) {

    try {
        File apiFile = new File(filename);
        Scanner sc = new Scanner(apiFile);

        apiurl = sc.nextLine();
        apikey = sc.nextLine();

        sc.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}