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:de.tudarmstadt.ukp.dkpro.core.io.text.TokenizedTextWriter.java

/**
 * Read a file containing stopwords (one per line).
 * <p>/*from   w  w w.  j av  a 2 s. c o m*/
 * Empty lines and lines starting with ("#") are filtered out.
 * 
 * @param f
 * @return
 * @throws IOException
 */
private static Set<String> readStopwordsFile(File f) throws IOException {
    return Files.readAllLines(f.toPath()).stream().map(String::trim).filter(l -> !l.isEmpty())
            .filter(l -> !l.startsWith("#")).map(w -> w.toLowerCase()).collect(Collectors.toSet());
}

From source file:io.syndesis.runtime.action.DynamicActionSqlStoredITCase.java

private static String read(final String path) {
    try {/*from  ww w  . jav  a  2  s.c  o  m*/
        return String.join("",
                Files.readAllLines(Paths.get(DynamicActionSqlStoredITCase.class.getResource(path).toURI())));
    } catch (IOException | URISyntaxException e) {
        throw new IllegalArgumentException("Unable to read from path: " + path, e);
    }
}

From source file:net.dv8tion.jda.player.Bot.java

public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
    //If the person who sent the message isn't a known auth'd user, ignore.
    try {//from w  w  w .  j  av  a2  s  . c  om
        //We specifically reread the admins.txt each time a command is run so that we can update the admins.txt
        // while the bot is running. Basically this is just me being lazy.
        if (!Files.readAllLines(Paths.get("admins.txt")).contains(event.getAuthor().getId()))
            return;
    } catch (IOException e) {
        //Fail silently. Allows the admin system to be "disabled" when admins.txt does not exist.
        //            e.printStackTrace();
    }

    String message = event.getMessage().getContent();
    AudioManager manager = event.getGuild().getAudioManager();
    MusicPlayer player;
    if (manager.getSendingHandler() == null) {
        player = new MusicPlayer();
        player.setVolume(DEFAULT_VOLUME);
        manager.setSendingHandler(player);
    } else {
        player = (MusicPlayer) manager.getSendingHandler();
    }

    if (message.startsWith("volume ")) {
        float volume = Float.parseFloat(message.substring("volume ".length()));
        volume = Math.min(1F, Math.max(0F, volume));
        player.setVolume(volume);
        event.getChannel().sendMessage("Volume was changed to: " + volume);
    }

    if (message.equals("list")) {
        List<AudioSource> queue = player.getAudioQueue();
        if (queue.isEmpty()) {
            event.getChannel().sendMessage("The queue is currently empty!");
            return;
        }

        MessageBuilder builder = new MessageBuilder();
        builder.appendString("__Current Queue.  Entries: " + queue.size() + "__\n");
        for (int i = 0; i < queue.size() && i < 10; i++) {
            AudioInfo info = queue.get(i).getInfo();
            //                builder.appendString("**(" + (i + 1) + ")** ");
            if (info == null)
                builder.appendString("*Could not get info for this song.*");
            else {
                AudioTimestamp duration = info.getDuration();
                builder.appendString("`[");
                if (duration == null)
                    builder.appendString("N/A");
                else
                    builder.appendString(duration.getTimestamp());
                builder.appendString("]` " + info.getTitle() + "\n");
            }
        }

        boolean error = false;
        int totalSeconds = 0;
        for (AudioSource source : queue) {
            AudioInfo info = source.getInfo();
            if (info == null || info.getDuration() == null) {
                error = true;
                continue;
            }
            totalSeconds += info.getDuration().getTotalSeconds();
        }

        builder.appendString(
                "\nTotal Queue Time Length: " + AudioTimestamp.fromSeconds(totalSeconds).getTimestamp());
        if (error)
            builder.appendString("`An error occured calculating total time. Might not be completely valid.");
        event.getChannel().sendMessage(builder.build());
    }
    if (message.equals("nowplaying")) {
        if (player.isPlaying()) {
            AudioTimestamp currentTime = player.getCurrentTimestamp();
            AudioInfo info = player.getCurrentAudioSource().getInfo();
            if (info.getError() == null) {
                event.getChannel().sendMessage("**Playing:** " + info.getTitle() + "\n" + "**Time:**    ["
                        + currentTime.getTimestamp() + " / " + info.getDuration().getTimestamp() + "]");
            } else {
                event.getChannel()
                        .sendMessage("**Playing:** Info Error. Known source: "
                                + player.getCurrentAudioSource().getSource() + "\n" + "**Time:**    ["
                                + currentTime.getTimestamp() + " / (N/A)]");
            }
        } else {
            event.getChannel().sendMessage("The player is not currently playing anything!");
        }
    }

    //Start an audio connection with a VoiceChannel
    if (message.startsWith("join ")) {
        //Separates the name of the channel so that we can search for it
        String chanName = message.substring(5);

        //Scans through the VoiceChannels in this Guild, looking for one with a case-insensitive matching name.
        VoiceChannel channel = event.getGuild().getVoiceChannels().stream()
                .filter(vChan -> vChan.getName().equalsIgnoreCase(chanName)).findFirst().orElse(null); //If there isn't a matching name, return null.
        if (channel == null) {
            event.getChannel()
                    .sendMessage("There isn't a VoiceChannel in this Guild with the name: '" + chanName + "'");
            return;
        }
        manager.openAudioConnection(channel);
    }
    //Disconnect the audio connection with the VoiceChannel.
    if (message.equals("leave"))
        manager.closeAudioConnection();

    if (message.equals("skip")) {
        player.skipToNext();
        event.getChannel().sendMessage("Skipped the current song.");
    }

    if (message.equals("repeat")) {
        if (player.isRepeat()) {
            player.setRepeat(false);
            event.getChannel().sendMessage("The player has been set to **not** repeat.");
        } else {
            player.setRepeat(true);
            event.getChannel().sendMessage("The player been set to repeat.");
        }
    }

    if (message.equals("shuffle")) {
        if (player.isShuffle()) {
            player.setShuffle(false);
            event.getChannel().sendMessage("The player has been set to **not** shuffle.");
        } else {
            player.setShuffle(true);
            event.getChannel().sendMessage("The player been set to shuffle.");
        }
    }

    if (message.equals("reset")) {
        player.stop();
        player = new MusicPlayer();
        player.setVolume(DEFAULT_VOLUME);
        manager.setSendingHandler(player);
        event.getChannel().sendMessage("Music player has been completely reset.");
    }

    //Start playing audio with our FilePlayer. If we haven't created and registered a FilePlayer yet, do that.
    if (message.startsWith("play")) {
        //If no URL was provided.
        if (message.equals("play")) {
            if (player.isPlaying()) {
                event.getChannel().sendMessage("Player is already playing!");
                return;
            } else if (player.isPaused()) {
                player.play();
                event.getChannel().sendMessage("Playback as been resumed.");
            } else {
                if (player.getAudioQueue().isEmpty())
                    event.getChannel()
                            .sendMessage("The current audio queue is empty! Add something to the queue first!");
                else {
                    player.play();
                    event.getChannel().sendMessage("Player has started playing!");
                }
            }
        } else if (message.startsWith("play ")) {
            String msg = "";
            String url = message.substring("play ".length());
            Playlist playlist = Playlist.getPlaylist(url);
            List<AudioSource> sources = new LinkedList(playlist.getSources());
            //                AudioSource source = new RemoteSource(url);
            //                AudioSource source = new LocalSource(new File(url));
            //                AudioInfo info = source.getInfo();   //Preload the audio info.
            if (sources.size() > 1) {
                event.getChannel().sendMessage("Found a playlist with **" + sources.size() + "** entries.\n"
                        + "Proceeding to gather information and queue sources. This may take some time...");
                final MusicPlayer fPlayer = player;
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        for (Iterator<AudioSource> it = sources.iterator(); it.hasNext();) {
                            AudioSource source = it.next();
                            AudioInfo info = source.getInfo();
                            List<AudioSource> queue = fPlayer.getAudioQueue();
                            if (info.getError() == null) {
                                queue.add(source);
                                if (fPlayer.isStopped())
                                    fPlayer.play();
                            } else {
                                event.getChannel().sendMessage(
                                        "Error detected, skipping source. Error:\n" + info.getError());
                                it.remove();
                            }
                        }
                        event.getChannel()
                                .sendMessage("Finished queuing provided playlist. Successfully queued **"
                                        + sources.size() + "** sources");
                    }
                };
                thread.start();
            } else {
                AudioSource source = sources.get(0);
                AudioInfo info = source.getInfo();
                if (info.getError() == null) {
                    player.getAudioQueue().add(source);
                    msg += "The provided URL has been added the to queue";
                    if (player.isStopped()) {
                        player.play();
                        msg += " and the player has started playing";
                    }
                    event.getChannel().sendMessage(msg + ".");
                } else {
                    event.getChannel().sendMessage("There was an error while loading the provided URL.\n"
                            + "Error: " + info.getError());
                }
            }
        }
    }
    if (message.equals("pause")) {
        player.pause();
        event.getChannel().sendMessage("Playback has been paused.");
    }
    if (message.equals("stop")) {
        player.stop();
        event.getChannel().sendMessage("Playback has been completely stopped.");
    }
    if (message.equals("restart")) {
        if (player.isStopped()) {
            if (player.getPreviousAudioSource() != null) {
                player.reload(true);
                event.getChannel().sendMessage("The previous song has been restarted.");
            } else {
                event.getChannel()
                        .sendMessage("The player has never played a song, so it cannot restart a song.");
            }
        } else {
            player.reload(true);
            event.getChannel().sendMessage("The currently playing song has been restarted!");
        }
    }
}

From source file:org.elasticsearch.discovery.ec2.Ec2DiscoveryClusterFormationTests.java

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 *///ww w.j  a  v  a2  s.c o m
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    httpServer = MockHttpServer
            .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);

    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()),
                StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();

            String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();

                sw.writeStartElement("reservationSet");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());

                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();

                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();

                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();

                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();

                                            sw.writeEmptyElement("groupName");

                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();

            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });

    httpServer.start();
}

From source file:org.apdplat.superword.tools.WordSources.java

private static List<String> getExistWords(URL url) {
    try {//from w ww .  j av  a2  s.com
        return Files.readAllLines(Paths.get(url.toURI()));
    } catch (Exception e) {
        return Collections.emptyList();
    }
}

From source file:sample.fa.ScriptRunnerApplication.java

void loadScript(File f) {
    try {//from  w ww  .  j  a  va2  s  .  com
        scriptContents.setText(String.join("\n", Files.readAllLines(f.toPath())));

        String name = f.getName();
        int lastDot = name.lastIndexOf('.');
        if (lastDot >= 0) {
            String extension = name.substring(lastDot + 1);
            for (int i = 0; i < languagesModel.getSize(); i++) {
                ScriptEngine se = languagesModel.getElementAt(i);
                if (se.getFactory().getExtensions().indexOf(extension) >= 0) {
                    languagesModel.setSelectedItem(se);
                    break;
                }
            }
        }
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(scriptContents, ex.getMessage(), "Error Loading Script",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java

protected String[] readFromCsv(String username) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath()));
    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i);
        String[] cols = line.split(",");
        if (cols[0].matches("\"" + username + "\"")) {
            return unescape(cols);
        }// w  ww.jav a 2s .  c o  m
    }
    return null;
}

From source file:com.evolveum.midpoint.provisioning.impl.manual.TestSemiManual.java

private void replaceInCsv(String[] data) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath()));
    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i);
        String[] cols = line.split(",");
        if (cols[0].matches("\"" + data[0] + "\"")) {
            lines.set(i, formatCsvLine(data));
        }/*from w w w. j  av  a  2s  .  c  o  m*/
    }
    Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE);
}

From source file:io.apiman.common.es.util.ApimanEmbeddedElastic.java

private void checkForDanglingProcesses() throws IOException {
    if (Files.exists(pidPath)) {
        for (String pid : Files.readAllLines(pidPath)) {
            System.err.println(//from   w  ww.j  a  va 2  s.  c  o  m
                    "Attempting to kill Elasticsearch process left over from previous execution: " + pid);
            Process result = Runtime.getRuntime().exec("kill " + pid);
            IOUtils.copy(result.getInputStream(), System.out);
            IOUtils.copy(result.getErrorStream(), System.err);
            result.destroy();
        }
        Files.deleteIfExists(pidPath);
    }
}

From source file:System.ConsoleHelper.java

@Override
public List<String> getTurtleScript(String scriptName) {
    List<String> result = null;
    try {//from ww w.j  a  v  a 2 s . co m
        result = Files.readAllLines(Paths.get(clientID + "/" + scriptName));
    } catch (IOException ex) {
        System.err.println("ConsoleHelper : Error retrieving client's file " + ex.getMessage());
    }
    return result;
}