Example usage for java.nio.file Files readAllLines

List of usage examples for java.nio.file Files readAllLines

Introduction

In this page you can find the example usage for java.nio.file Files readAllLines.

Prototype

public static List<String> readAllLines(Path path) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:org.languagetool.dev.bigdata.ConfusionFileIndenter.java

public static void main(String[] args) throws IOException {
    if (args.length != 1) {
        System.out.println("Usage: " + ConfusionFileIndenter.class.getSimpleName() + " <file>");
        System.exit(1);/*from  w w w.ja  v  a 2s  .co  m*/
    }
    List<String> lines = Files.readAllLines(Paths.get(args[0]));
    System.out.println(indent(lines));
}

From source file:mcnutty.music.get.MusicGet.java

public static void main(String[] args) throws Exception {

    //print out music-get
    System.out.println("                     _                      _   ");
    System.out.println(" _ __ ___  _   _ ___(_) ___       __ _  ___| |_ ");
    System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|");
    System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| |  __/ |_ ");
    System.out.println("|_| |_| |_|\\__,_|___/_|\\___|     \\__, |\\___|\\__|");
    System.out.println("                                 |___/          \n");

    //these will always be initialised later (but the compiler doesn't know that)
    String directory = "";
    Properties prop = new Properties();

    try (InputStream input = new FileInputStream("config.properties")) {
        prop.load(input);//from www. j  av  a 2  s  . c o m
        if (prop.getProperty("directory") != null) {
            directory = prop.getProperty("directory");
        } else {
            System.out.println(
                    "Error reading config property 'directory' - using default value of /tmp/musicserver/\n");
            directory = "/tmp/musicserver/";
        }
        if (prop.getProperty("password") == null) {
            System.out.println("Error reading config property 'password' - no default value, exiting\n");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println("Error reading config file");
        System.exit(1);
    }

    //create a queue object
    ProcessQueue process_queue = new ProcessQueue();

    try {
        if (args.length > 0 && args[0].equals("clean")) {
            Files.delete(Paths.get("queue.json"));
        }
        //load an existing queue if possible
        String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString();
        JSONArray queue_state = new JSONArray(raw_queue);
        ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>();
        JSONArray queue = queue_state.getJSONArray(0);
        for (int i = 0; i < queue.length(); i++) {
            JSONObject item = ((JSONObject) queue.get(i));
            QueueItem loaded_item = new QueueItem();
            loaded_item.ip = item.getString("ip");
            loaded_item.real_name = item.getString("name");
            loaded_item.disk_name = item.getString("guid");
            loaded_queue.add(loaded_item);
        }
        process_queue.bucket_queue = loaded_queue;
        System.out.println("Loaded queue from disk\n");
    } catch (Exception ex) {
        //otherwise clean out the music directory and start a new queue
        try {
            Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
            Files.delete(Paths.get(directory));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Files.createDirectory(Paths.get(directory));
        System.out.println("Created a new queue\n");
    }

    //start the web server
    StartServer start_server = new StartServer(process_queue, directory);
    new Thread(start_server).start();

    //wit for the web server to spool up
    Thread.sleep(1000);

    //read items from the queue and play them
    while (true) {
        QueueItem next_item = process_queue.next_item();
        if (!next_item.equals(new QueueItem())) {
            //Check the timeout
            int timeout = 547;
            try (FileInputStream input = new FileInputStream("config.properties")) {
                prop.load(input);
                timeout = Integer.parseInt(prop.getProperty("timeout", "547"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Playing " + next_item.real_name);
            process_queue.set_played(next_item);
            process_queue.save_queue();
            Process p = Runtime.getRuntime().exec("timeout " + timeout
                    + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name);

            try {
                p.waitFor(timeout, TimeUnit.SECONDS);
                Files.delete(Paths.get(directory + next_item.disk_name));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            process_queue.bucket_played.clear();
        }
        Thread.sleep(1000);
    }
}

From source file:com.thesmartweb.vivliocrawlermaven.VivlioCrawlerMavenMain.java

/**
 * @param args the command line arguments
 *//*w w  w.  j a  v a  2s.  c  o m*/
public static void main(String[] args) {
    // TODO code application logic here
    try {

        OaiPmhServer server = new OaiPmhServer("http://vivliothmmy.ee.auth.gr/cgi/oai2");
        RecordsList listRecords = server.listRecords("oai_dc");//we capture all the records in oai dc format
        List<VivlioCrawlerMavenMain> listtotal = new ArrayList<VivlioCrawlerMavenMain>();
        //we capture all the names of the professors and former professor of ECE of AUTH from a txt file
        //change the directory to yours
        List<String> profs = Files.readAllLines(Paths.get(
                "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/profs.txt"));

        boolean more = true;//it is a flag used if we encounter more entries than the initial capture
        JSONArray array = new JSONArray();//it is going to be our final total json array
        JSONObject jsonObject = new JSONObject();//it is going to be our final total json object
        while (more) {
            for (Record rec : listRecords.asList()) {
                VivlioCrawlerMavenMain vc = new VivlioCrawlerMavenMain();
                Element metadata = rec.getMetadata();
                if (metadata != null) {
                    //System.out.println(rec.getMetadataAsString());
                    List<Element> elements = metadata.elements();
                    //System.out.println(metadata.getStringValue());
                    for (Element element : elements) {
                        String name = element.getName();
                        //we get the title, remove \r, \n and beginning and trailing whitespace
                        if (name.equalsIgnoreCase("title")) {
                            vc.title = element.getStringValue();
                            vc.title = vc.title.trim();
                            vc.title = vc.title.replaceAll("(\\r|\\n)", "");
                            if (!(vc.title.endsWith("."))) {
                                vc.title = vc.title + ".";//we also add dot in the end for the titles to be uniformed
                            }
                        }
                        if (name.equalsIgnoreCase("creator")) {
                            vc.creators.add(element.getStringValue());//we capture the students' names
                        }
                        if (name.equalsIgnoreCase("subject")) {
                            vc.subjects.add(element.getStringValue());//we capture the subjects
                        }
                        if (name.equalsIgnoreCase("description")) {
                            vc.description = element.getStringValue();//we capture the abstract
                        }
                        if (name.equalsIgnoreCase("date")) {
                            vc.datestring = element.getStringValue();
                        }
                        if (name.equalsIgnoreCase("identifier")) {
                            if (element.getStringValue().contains("http://")) {
                                vc.thesisFiles.add(element.getStringValue());//we capture the url of the thesis whole file
                                if (vc.thesisURL == null) {
                                    vc.thesisURL = element.getStringValue().substring(0, 32);
                                }
                            }
                            //if the identifier contains the title then it must be the citation 
                            //out of the citation we need to extract the supevisor's name
                            if (element.getStringValue().contains(vc.title.substring(0, 10))) {
                                vc.citation = element.getStringValue();
                                vc.supervisor = element.getStringValue();
                                Iterator profsIterator = profs.iterator();
                                vc.supervisor = vc.supervisor.replace(vc.title, "");//we remove the title out of the citation
                                //if we have two students we remove the first occurence of "" which stands for "and"
                                if (vc.creators.size() == 2) {
                                    vc.supervisor = vc.supervisor.replaceFirst("", "");
                                }
                                //we remove the students' names
                                Iterator creatorsIterator = vc.creators.iterator();
                                while (creatorsIterator.hasNext()) {
                                    vc.supervisor = vc.supervisor.replace(creatorsIterator.next().toString(),
                                            "");
                                }
                                boolean profFlag = false;//flag used that declares that we found the professor that was supervisor
                                while (profsIterator.hasNext() && !profFlag) {
                                    String prof = profsIterator.next().toString();
                                    //we split the professor's name to surname and name
                                    //because some entries have first the surname and others first the name
                                    String[] profSplitted = prof.split("\\s+");
                                    String supervisorCleared = vc.supervisor;
                                    supervisorCleared = supervisorCleared.replaceAll("\\s+", "");//we clear the white space
                                    supervisorCleared = supervisorCleared.replaceAll("(\\r|\\n)", "");//we remove the \r\n
                                    //now we check if the citation includes any name of the professors from the txt
                                    if (supervisorCleared.contains(profSplitted[0])
                                            && supervisorCleared.contains(profSplitted[1])) {
                                        vc.supervisor = prof;
                                        profFlag = true;
                                    }
                                }
                                //if we don't find the name of the supervisor, we have to perform string manipulation to extract it
                                if (!profFlag) {
                                    vc.supervisor = vc.supervisor.trim();
                                    //we remove the word "" which stands for "Thessaloniki" and "" which stands for Greece
                                    if (vc.supervisor.contains("")) {
                                        vc.supervisor = vc.supervisor.replaceFirst("",
                                                "");
                                    }
                                    if (vc.supervisor.contains("")) {
                                        vc.supervisor = vc.supervisor.replaceFirst("",
                                                "");
                                    }
                                    if (vc.supervisor.contains("")) {
                                        vc.supervisor = vc.supervisor.replaceFirst("", "");
                                    }
                                    if (vc.supervisor.contains("")) {
                                        vc.supervisor = vc.supervisor.replaceFirst("", "");
                                    }
                                    //we remove the year and then we should be left only with the supervisor's name
                                    vc.supervisor = vc.supervisor.replace("(", "");
                                    vc.supervisor = vc.supervisor.trim();
                                    vc.supervisor = vc.supervisor.replace(")", "");
                                    vc.supervisor = vc.supervisor.trim();
                                    vc.supervisor = vc.supervisor.replace(",", "");
                                    vc.supervisor = vc.supervisor.trim();
                                    vc.supervisor = vc.supervisor.replace(".", "");
                                    vc.supervisor = vc.supervisor.trim();
                                    vc.supervisor = vc.supervisor.replace(vc.datestring.substring(0, 4), "");
                                    vc.supervisor = vc.supervisor.trim();
                                }
                                //we put everything in a json object
                                JSONObject obj = new JSONObject();
                                obj.put("title", vc.title);
                                obj.put("description", vc.description);
                                JSONArray creatorsArray = new JSONArray();
                                creatorsArray.add(vc.creators);
                                obj.put("creators", creatorsArray);
                                JSONArray subjectsArray = new JSONArray();
                                List<String> subjectsList = new ArrayList<String>(vc.subjects);
                                subjectsArray.add(subjectsList);
                                obj.put("subjects", subjectsArray);
                                obj.put("datestring", vc.datestring);
                                JSONArray thesisFilesArray = new JSONArray();
                                thesisFilesArray.add(vc.thesisFiles);
                                obj.put("thesisFiles", thesisFilesArray);
                                obj.put("thesisURL", vc.thesisURL);
                                obj.put("supervisor", vc.supervisor);
                                obj.put("citation", vc.citation);
                                //if you are using JSON.simple do this
                                array.add(obj);
                            }
                        }
                    }
                    listtotal.add(vc);//a list containing all the objects
                    //it is not used for now, but created for potential extension of the work
                }
            }
            //the following if clause searches for new records
            if (listRecords.getResumptionToken() != null) {
                listRecords = server.listRecords(listRecords.getResumptionToken());
            } else {
                more = false;
            }
        }
        //we print which records did not have a supervisor
        for (VivlioCrawlerMavenMain vctest : listtotal) {

            if (vctest.supervisor == null) {
                System.out.println(vctest.title);
                System.out.println(vctest.citation);
            }
        }
        //we create a pretty json with GSON and we write it into a file
        jsonObject.put("VivliothmmyOldArray", array);
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(jsonObject.toJSONString()).getAsJsonObject();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String prettyJson = gson.toJson(json);
        try {

            FileWriter file = new FileWriter(
                    "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/VivliothmmyOldRecords.json");
            file.write(prettyJson);
            file.flush();
            file.close();

        } catch (IOException e) {
            System.out.println("Exception: " + e);
        }

        //System.out.print(prettyJson);

        //int j=0;

    } catch (OAIException | IOException e) {
        System.out.println("Exception: " + e);
    }
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;/*from  w ww  .  j a v a  2 s  .  c  o  m*/
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}

From source file:Main.java

/**
 * Converts a file to a string/*from   w w  w. j  a v a  2 s.  c  om*/
 * @param f The file
 * @return The string
 * @throws IOException Thrown in any IOException occurs
 */
public static String fileToString(File f) throws IOException {
    ArrayList<String> list = new ArrayList<>(Files.readAllLines(f.toPath()));
    StringBuilder builder = new StringBuilder();
    list.forEach(builder::append);
    return builder.toString();
}

From source file:org.apdplat.superword.rule.RootRule.java

public static List<Word> getAllRoots() {
    List<Word> roots = new ArrayList<>();
    try {/*  ww  w .jav a  2  s .  c o  m*/
        List<String> lines = Files.readAllLines(Paths.get("src/main/resources/root_affix.txt"));
        lines.forEach(line -> {
            if (StringUtils.isNotBlank(line) && !line.startsWith("#") && line.startsWith("?")) {
                String[] attr = line.substring(3).split("??");
                if (attr != null && attr.length == 2) {
                    String root = attr[0];
                    String meaning = attr[1];
                    roots.add(new Word(root, meaning));
                    LOGGER.debug("?" + root + meaning);
                } else {
                    LOGGER.error("??" + line);
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return roots;
}

From source file:org.apdplat.superword.rule.SuffixRule.java

public static List<Suffix> getAllSuffixes() {
    List<Suffix> suffixes = new ArrayList<>();
    try {/*from   ww  w . j  ava 2s  .  c om*/
        List<String> lines = Files.readAllLines(Paths.get("src/main/resources/root_affix.txt"));
        lines.forEach(line -> {
            if (StringUtils.isNotBlank(line) && !line.startsWith("#") && line.startsWith("?")) {
                String[] attr = line.substring(3).split("??");
                if (attr != null && attr.length == 2) {
                    String suffix = attr[0];
                    String meaning = attr[1];
                    if (suffix.contains(",")) {
                        suffixes.addAll(new ComplexSuffix(suffix, meaning).simplify());
                        LOGGER.debug("???" + suffix + meaning);
                    } else {
                        suffixes.add(new Suffix(suffix, meaning));
                        LOGGER.debug("?" + suffix + meaning);
                    }
                } else {
                    LOGGER.error("??" + line);
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return suffixes;
}

From source file:org.apdplat.superword.rule.PrefixRule.java

public static List<Prefix> getAllPrefixes() {
    List<Prefix> prefixes = new ArrayList<>();
    try {/*from w w  w.  j a  v a 2  s  .  c o  m*/
        List<String> lines = Files.readAllLines(Paths.get("src/main/resources/root_affix.txt"));
        lines.forEach(line -> {
            if (StringUtils.isNotBlank(line) && !line.startsWith("#") && line.startsWith("?")) {
                String[] attr = line.substring(3).split("??");
                if (attr != null && attr.length == 2) {
                    String prefix = attr[0];
                    String meaning = attr[1];
                    if (prefix.contains(",")) {
                        prefixes.addAll(new ComplexPrefix(prefix, meaning).simplify());
                        LOGGER.debug("???" + prefix + meaning);
                    } else {
                        prefixes.add(new Prefix(prefix, meaning));
                        LOGGER.debug("?" + prefix + meaning);
                    }
                } else {
                    LOGGER.error("??" + line);
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return prefixes;
}

From source file:model.fileloader.FileLoader.java

protected List<String> getFileContent(String filename) throws IOException {
    if (!StringUtils.hasText(filename))
        throw new IOException();

    String workDir = System.getProperty("user.dir");
    File file = new File(workDir, filename);
    Path path = file.toPath();/*w w w  . java  2 s . c om*/
    return Files.readAllLines(path);
}

From source file:de.jfachwert.bank.GeldbetragIT.java

private static int getNumberOfFailedTests() throws IOException {
    Path resultsFile = Paths.get("target", "tck-results.txt");
    List<String> lines = Files.readAllLines(resultsFile);
    String testsFailedLine = lines.get(lines.size() - 1);
    String n = StringUtils.substringAfter(testsFailedLine, ":").trim();
    return Integer.parseInt(n);
}