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, Charset cs) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:faa.cucumber.pages.FaaHomePage.java

public void selectFromRoleTypeCode() {
    //String returnValue = "null";
    try {/*from   w ww. ja v  a 2  s  . co m*/
        //I would prefer to read my file using NIO, which is faster
        Path pathToMyTextFile = Paths
                .get((System.getProperty("user.dir") + "/src/test/java/faa/utils/role_types.txt"));
        //Path pathToMyTextFile = Paths.get("C:/Users/jfrankl6/workspacex/faa-gradle-newtest/src/test/java/faa/utils/role_types.txt");
        //Then I would like to obtain the lines in Array, also I could have them available for process later
        List<String> linesInFile = Files.readAllLines(pathToMyTextFile, StandardCharsets.ISO_8859_1);
        //If I want to access a random element, I would use random methods to access a random index of the list and retrieve that element
        Random randomUtil = new Random();

        //I will use the formula for random and define the maximum (which will be the length of the array -1) and the minimum which will be zero
        //since the indexes are represented from 0 to length - 1
        int max = linesInFile.size() - 1;
        int min = 0;
        System.out.println("Role Code Random min-->" + max);
        System.out.println("Role Code Random max-->" + min);
        System.out.println("Role Code  Random linesInFile.size()-->" + linesInFile.size());

        //You can simplify this formula later, I'm just putting the whole thing
        int randomIndexForWord = randomUtil.nextInt((max - min + 1)) + min;

        //Here I get a random Noun
        String randomWord = linesInFile.get(randomIndexForWord);
        System.out.println("randomWord Random Role Types 4-->" + randomWord);
        //              System.out.println("returnValue Random Role Types -->" + returnValue);
        //              returnValue = randomWord;
        //              System.out.println("returnValue Random Role Types -->" + returnValue);
        Select dropDownList = new Select(inviteRoleCode);
        dropDownList.selectByVisibleText(randomWord);
        System.out.println("Selected from Role Type Drop Down List-->" + randomWord);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //         Select dropDownList = new Select(inviteRoleType);
    //         dropDownList.selectByVisibleText(roleType);
    //         System.out.println("Selected from Role Type Drop Down List-->" + roleType);
    //return returnValue;
}

From source file:neembuu.uploader.NeembuuUploader.java

void checkBox_selectFromPreviousState() {
    try {//from   w  ww  .  ja v  a  2s  .  c  o  m
        List<String> lines = Files.readAllLines(Application.getNeembuuHome().resolve("selectedhostslist"),
                Charset.forName("UTF-8"));

        OUTER_LOOP: for (String host : lines) {
            INNER_LOOP: for (Map.Entry<JCheckBox, SmallModuleEntry> entry : unsyncEntries_map()) {
                JCheckBox jCheckBox = entry.getKey();
                SmallModuleEntry smallModuleEntry = entry.getValue();
                if (smallModuleEntry.getName().equalsIgnoreCase(host)) {
                    jCheckBox.setSelected(true);
                    checkBoxActionListener.actionPerformed(null);
                    continue OUTER_LOOP;
                }
            }

        }

    } catch (IOException ex) {
        Logger.getLogger(NeembuuUploader.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ffx.algorithms.RotamerOptimization.java

/**
 * Loads the number of iterations a box optimization or sliding window has
 * gone through if using an energy restart file: NOT IMPLEMENTED.
 *
 * @param restartFile/*from www  . ja v  a 2  s . c  o m*/
 * @return Number of iterations of the sliding window or box optimization.
 */
public int loadEnergyRestartIterations(File restartFile) {
    int numIterations = -1;
    try {
        Path path = Paths.get(restartFile.getCanonicalPath());
        List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        for (String line : lines) {
            String tok[] = line.split("\\s");
            if (tok[0].startsWith("Iteration")) {
                numIterations = Integer.parseInt(tok[1]);
                return numIterations;
            }
        }
    } catch (IOException ex) {
        logIfMaster(String.format(
                " Error in loading number of iterations of box optimization or sliding window: %s",
                ex.toString()), Level.WARNING);
    }
    return numIterations;
}

From source file:ffx.algorithms.RotamerOptimization.java

public int loadEnergyRestart(File restartFile, Residue residues[], int boxIteration, int[] cellIndices) {
    try {//from www  .ja v  a  2  s  .c  om
        int nResidues = residues.length;
        Path path = Paths.get(restartFile.getCanonicalPath());
        List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        List<String> linesThisBox = new ArrayList<>();

        if (usingBoxOptimization && boxIteration >= 0) {
            boolean foundBox = false;
            for (int i = 0; i < lines.size(); i++) {
                String line = lines.get(i);
                if (line.startsWith("Box")) {
                    String tok[] = line.replaceAll("Box", "").replaceAll(":", ",").replaceAll(" ", "")
                            .split(",");
                    int readIteration = Integer.parseInt(tok[0]);
                    int readCellIndexX = Integer.parseInt(tok[1]);
                    int readCellIndexY = Integer.parseInt(tok[2]);
                    int readCellIndexZ = Integer.parseInt(tok[3]);
                    if (readIteration == boxIteration && readCellIndexX == cellIndices[0]
                            && readCellIndexY == cellIndices[1] && readCellIndexZ == cellIndices[2]) {
                        foundBox = true;
                        for (int j = i + 1; j < lines.size(); j++) {
                            String l = lines.get(j);
                            if (l.startsWith("Box")) {
                                break;
                            }
                            linesThisBox.add(l);
                        }
                        break;
                    }
                }
            }
            if (!foundBox) {
                logIfMaster(String.format(" Didn't find restart energies for Box %d: %d,%d,%d", boxIteration,
                        cellIndices[0], cellIndices[1], cellIndices[2]));
                return 0;
            } else if (linesThisBox.size() == 0) {
                return 0;
            } else {
                lines = linesThisBox;
            }
        }

        List<String> singleLines = new ArrayList<>();
        List<String> pairLines = new ArrayList<>();
        List<String> tripleLines = new ArrayList<>();
        for (String line : lines) {
            String tok[] = line.split("\\s");
            if (tok[0].startsWith("Self")) {
                singleLines.add(line);
            } else if (tok[0].startsWith("Pair")) {
                pairLines.add(line);
            } else if (tok[0].startsWith("Triple")) {
                tripleLines.add(line);
            }
        }
        int loaded = 0;
        if (tripleLines.size() > 0) {
            loaded = 3;
        } else if (pairLines.size() > 0) {
            loaded = 2;
        } else if (singleLines.size() > 0) {
            loaded = 1;
        } else {
            logger.warning(String.format("Empty or unreadable energy restart file: %s.",
                    restartFile.getCanonicalPath()));
        }
        if (loaded >= 1) {
            jobMapSingles.clear();
            // allocate selfEnergy array and create self jobs
            HashMap<String, Integer> reverseJobMapSingles = new HashMap<>();
            int singleJobIndex = 0;
            selfEnergy = new double[nResidues][];
            for (int i = 0; i < nResidues; i++) {
                Residue resi = residues[i];
                Rotamer roti[] = resi.getRotamers(library);
                selfEnergy[i] = new double[roti.length];
                for (int ri = 0; ri < roti.length; ri++) {
                    Integer selfJob[] = { i, ri };
                    if (decomposeOriginal && ri != 0) {
                        continue;
                    }
                    jobMapSingles.put(singleJobIndex, selfJob);
                    String revKey = String.format("%d %d", i, ri);
                    reverseJobMapSingles.put(revKey, singleJobIndex);
                    singleJobIndex++;
                }
            }
            // fill in self-energies from file while removing the corresponding jobs from jobMapSingles
            for (String line : singleLines) {
                try {
                    String tok[] = line.replace(",", "").replace(":", "").split("\\s+");
                    int i;
                    if (tok[1].contains("-")) {
                        i = nameToNumber(tok[1], residues);
                    } else {
                        i = Integer.parseInt(tok[1]);
                    }
                    int ri = Integer.parseInt(tok[2]);
                    double energy = Double.parseDouble(tok[3]);
                    try {
                        selfEnergy[i][ri] = energy;
                    } catch (ArrayIndexOutOfBoundsException ex) {
                        logger.log(Level.SEVERE,
                                String.format(
                                        "Restart file contained an out-of-bounds index.  Offending line: %s",
                                        line),
                                ex);
                    }
                    if (verbose) {
                        logIfMaster(String.format(" From restart file: Self energy %3d %-2d: %7s %-2d: %16.8f",
                                i, ri, residues[i], ri, energy));
                    }
                    // remove that job from the pool
                    String revKey = String.format("%d %d", i, ri);
                    Integer ret[] = jobMapSingles.remove(reverseJobMapSingles.get(revKey));
                    if (ret == null) {
                        //logIfMaster(String.format("(sdl %d) Restart file contained unnecessary value for %s", BOXNUM, revKey));
                    }
                } catch (NumberFormatException ex) {
                    logger.log(Level.WARNING,
                            String.format("Unparsable line in energy restart file: \n%s", line), ex);
                }
            }
            logIfMaster(" Loaded self energies from restart file.");
            // prune singles
            if (pruneClashes) {
                pruneSingleClashes(residues);
            }
        }
        if (loaded >= 2) {
            if (jobMapSingles.size() > 0) {
                if (master) {
                    logger.warning(
                            "Double-check that parameters match original run!  Found pairs in restart file, but singles job queue is non-empty.");
                }
            }
            jobMapPairs.clear();
            // allocated twoBodyEnergy array and create pair jobs
            HashMap<String, Integer> reverseJobMapPairs = new HashMap<>();
            int pairJobIndex = 0;
            twoBodyEnergy = new double[nResidues][][][];
            for (int i = 0; i < nResidues; i++) {
                Residue resi = residues[i];
                Rotamer roti[] = resi.getRotamers(library);
                twoBodyEnergy[i] = new double[roti.length][][];
                for (int ri = 0; ri < roti.length; ri++) {
                    if (pruneClashes && check(i, ri)) {
                        continue;
                    }
                    twoBodyEnergy[i][ri] = new double[nResidues][];
                    for (int j = i + 1; j < nResidues; j++) {
                        Residue resj = residues[j];
                        Rotamer rotj[] = resj.getRotamers(library);
                        twoBodyEnergy[i][ri][j] = new double[rotj.length];
                        for (int rj = 0; rj < rotj.length; rj++) {
                            if ((pruneClashes && check(j, rj)) || (prunePairClashes && check(i, ri, j, rj))) {
                                continue;
                            }
                            Integer pairJob[] = { i, ri, j, rj };
                            if (decomposeOriginal && (ri != 0 || rj != 0)) {
                                continue;
                            }
                            jobMapPairs.put(pairJobIndex, pairJob);
                            String revKey = String.format("%d %d %d %d", i, ri, j, rj);
                            reverseJobMapPairs.put(revKey, pairJobIndex);
                            pairJobIndex++;
                        }
                    }
                }
            }
            // fill in pair-energies from file while removing the corresponding jobs from jobMapPairs
            for (String line : pairLines) {
                try {
                    String tok[] = line.replace(",", "").replace(":", "").split("\\s+");
                    int i;
                    if (tok[1].contains("-")) {
                        i = nameToNumber(tok[1], residues);
                    } else {
                        i = Integer.parseInt(tok[1]);
                    }
                    int ri = Integer.parseInt(tok[2]);
                    int j;
                    if (tok[3].contains("-")) {
                        j = nameToNumber(tok[3], residues);
                    } else {
                        j = Integer.parseInt(tok[3]);
                    }
                    int rj = Integer.parseInt(tok[4]);
                    double energy = Double.parseDouble(tok[5]);
                    try {
                        twoBodyEnergy[i][ri][j][rj] = energy;
                    } catch (ArrayIndexOutOfBoundsException ex) {
                        logger.log(Level.SEVERE,
                                String.format(
                                        "Restart file contained an out-of-bounds index.  Offending line: %s",
                                        line),
                                ex);
                    }
                    if (verbose) {
                        logIfMaster(String.format(" From restart file: Pair energy %3d %-2d, %3d %-2d: %16.8f",
                                i, ri, j, rj, energy));
                    }
                    // remove that job from the pool
                    String revKey = String.format("%d %d %d %d", i, ri, j, rj);
                    Integer ret[] = jobMapPairs.remove(reverseJobMapPairs.get(revKey));
                    if (ret == null) {
                        //logIfMaster(String.format("(sdl %d) Restart file contained unnecessary value for %s", BOXNUM, revKey));
                    }
                } catch (NumberFormatException ex) {
                    logger.log(Level.WARNING,
                            String.format("Unparsable line in energy restart file: \n%s", line), ex);
                }
            }
            logIfMaster(" Loaded pair energies from restart file.");
            // prune pairs
            if (prunePairClashes) {
                prunePairClashes(residues);
            }
        }
        if (loaded >= 3) {
            if (jobMapPairs.size() > 0) {
                if (master) {
                    logger.warning(
                            "Double-check that parameters match original run!  Found trimers in restart file, but pairs job queue is non-empty.");
                }
            }
            HashMap<String, Integer> reverseJobMapTrimers = new HashMap<>();
            jobMapTrimers.clear();
            // allocate threeBodyEnergy array, fill in triple-energies from file
            int trimerJobIndex = 0;
            threeBodyEnergy = new double[nResidues][][][][][];
            for (int i = 0; i < nResidues; i++) {
                Residue resi = residues[i];
                Rotamer roti[] = resi.getRotamers(library);
                threeBodyEnergy[i] = new double[roti.length][][][][];
                for (int ri = 0; ri < roti.length; ri++) {
                    if (pruneClashes && check(i, ri)) {
                        continue;
                    }
                    threeBodyEnergy[i][ri] = new double[nResidues][][][];
                    for (int j = i + 1; j < nResidues; j++) {
                        Residue resj = residues[j];
                        Rotamer rotj[] = resj.getRotamers(library);
                        threeBodyEnergy[i][ri][j] = new double[rotj.length][][];
                        for (int rj = 0; rj < rotj.length; rj++) {
                            if ((pruneClashes && check(j, rj)) || (prunePairClashes && check(i, ri, j, rj))) {
                                continue;
                            }
                            threeBodyEnergy[i][ri][j][rj] = new double[nResidues][];
                            for (int k = j + 1; k < nResidues; k++) {
                                Residue resk = residues[k];
                                Rotamer rotk[] = resk.getRotamers(library);
                                threeBodyEnergy[i][ri][j][rj][k] = new double[rotk.length];
                                for (int rk = 0; rk < rotk.length; rk++) {
                                    if ((pruneClashes && check(k, rk)) || (prunePairClashes
                                            && (check(i, ri, k, rk) || check(j, rj, k, rk)))) {
                                        continue;
                                    }
                                    Integer trimerJob[] = { i, ri, j, rj, k, rk };
                                    if (decomposeOriginal && (ri != 0 || rj != 0 || rk != 0)) {
                                        continue;
                                    }
                                    jobMapTrimers.put(trimerJobIndex, trimerJob);
                                    String revKey = String.format("%d %d %d %d %d %d", i, ri, j, rj, k, rk);
                                    reverseJobMapTrimers.put(revKey, trimerJobIndex);
                                    trimerJobIndex++;
                                }
                            }
                        }
                    }
                }
            }
            // fill in triple-energies from file while removing the corresponding jobs from jobMapTrimers
            for (String line : tripleLines) {
                try {
                    String tok[] = line.replace(",", "").replace(":", "").split("\\s+");
                    int i;
                    if (tok[1].contains("-")) {
                        i = nameToNumber(tok[1], residues);
                    } else {
                        i = Integer.parseInt(tok[1]);
                    }
                    int ri = Integer.parseInt(tok[2]);
                    int j;
                    if (tok[3].contains("-")) {
                        j = nameToNumber(tok[3], residues);
                    } else {
                        j = Integer.parseInt(tok[3]);
                    }
                    int rj = Integer.parseInt(tok[4]);
                    int k;
                    if (tok[5].contains("-")) {
                        k = nameToNumber(tok[5], residues);
                    } else {
                        k = Integer.parseInt(tok[5]);
                    }
                    int rk = Integer.parseInt(tok[6]);
                    double energy = Double.parseDouble(tok[7]);
                    try {
                        threeBodyEnergy[i][ri][j][rj][k][rk] = energy;
                    } catch (ArrayIndexOutOfBoundsException ex) {
                        logger.log(Level.SEVERE,
                                String.format(
                                        "Restart file contained an out-of-bounds index.  Offending line: %s",
                                        line),
                                ex);
                    }
                    if (verbose) {
                        logIfMaster(String.format(
                                " From restart file: Trimer energy %3d %-2d, %3d %-2d, %3d %-2d: %16.8f", i, ri,
                                j, rj, k, rk, energy));
                    }
                    // remove that job from the pool
                    String revKey = String.format("%d %d %d %d %d %d", i, ri, j, rj, k, rk);
                    Integer ret[] = jobMapTrimers.remove(reverseJobMapTrimers.get(revKey));
                    if (ret == null) {
                        //logIfMaster(String.format("(sdl %d) Restart file contained unnecessary value for %s", BOXNUM, revKey));
                    }
                } catch (NumberFormatException ex) {
                    logger.log(Level.WARNING,
                            String.format("Unparsable line in energy restart file: \n%s", line), ex);
                }
            }
            logIfMaster(" Loaded trimer energies from restart file.");
        }
        return loaded;
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Exception while loading energy restart file.", ex);
    }
    return 0;
}