Example usage for org.apache.commons.io FileUtils readLines

List of usage examples for org.apache.commons.io FileUtils readLines

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readLines.

Prototype

public static List readLines(File file) throws IOException 

Source Link

Document

Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.

Usage

From source file:de.tudarmstadt.ukp.dkpro.tc.weka.task.serialization.LoadModelConnectorWeka.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    try {/*from w  w  w .j ava2 s  . co  m*/
        cls = (Classifier) weka.core.SerializationHelper
                .read(new File(tcModelLocation, MODEL_CLASSIFIER).getAbsolutePath());
    } catch (Exception e) {
        throw new ResourceInitializationException(e);
    }

    attributes = new ArrayList<>();
    try {
        for (String attributeName : FileUtils.readLines(new File(tcModelLocation, MODEL_FEATURE_NAMES))) {
            attributes.add(new Attribute(attributeName));
        }
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }

    classLabels = new ArrayList<>();
    try {
        for (String classLabel : FileUtils.readLines(new File(tcModelLocation, MODEL_CLASS_LABELS))) {
            classLabels.add(classLabel);
        }
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }

}

From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.util.SVMHMMUtils.java

/**
 * Creates a new file in the same directory as {@code featureVectorsFile} and replaces the first
 * token (outcome label) by its corresponding integer number from the bi-di map
 *
 * @param featureVectorsFile file/*w  w w  . j ava2 s.  c om*/
 * @param labelsToIntegers   mapping
 * @return new file
 */
public static File replaceLabelsWithIntegers(File featureVectorsFile, BidiMap labelsToIntegers)
        throws IOException {
    File result = new File(featureVectorsFile.getParent(), "mappedLabelsToInt_" + featureVectorsFile.getName());
    PrintWriter pw = new PrintWriter(new FileOutputStream(result));

    for (String line : FileUtils.readLines(featureVectorsFile)) {
        // split on the first whitespaces, keep the rest
        String[] split = line.split("\\s", 2);
        String label = split[0];
        String remainingContent = split[1];

        // find the integer
        Integer intOutput = (Integer) labelsToIntegers.get(label);

        // print to the output stream
        pw.printf("%d %s%n", intOutput, remainingContent);
    }

    IOUtils.closeQuietly(pw);

    return result;
}

From source file:hu.bme.mit.trainbenchmark.generator.sql.SQLGenerator.java

@Override
protected void persistModel() throws IOException, InterruptedException {
    final String footerFilePath = generatorConfig.getWorkspacePath()
            + "/hu.bme.mit.trainbenchmark.sql/src/main/resources/metamodel/railway-footer.sql";
    final File footerFile = new File(footerFilePath);

    final List<String> lines = FileUtils.readLines(footerFile);
    for (final String line : lines) {
        write(line);//w  w  w. ja v a  2 s.com
    }

    writer.close();

    compact();
}

From source file:aes.pica.touresbalon.tb_serviciosbolivariano.ServiciosBolivarianos.java

@Override
public List<ViajeVO> consultarViajes(String fechaViaje, String ciudadOrigen, String ciudadDestino,
        String horaSalida) {// www  . j a v a  2 s .c om
    List<ViajeVO> listaViajes = new ArrayList<>();
    String nombreArchivo = Constantes.NAME_VIAJES + fechaViaje + Constantes.CSV_FILE;
    try {
        File archivoConsulta = FileUtils.getFile(rutaConsulta, nombreArchivo);
        if (archivoConsulta != null && archivoConsulta.exists()) {
            List<String> lineasArchivo = FileUtils.readLines(archivoConsulta);
            System.out.println("Archivo encontrado: " + archivoConsulta.getAbsoluteFile());
            ViajeVO viajeAux;
            for (String s : lineasArchivo) {
                viajeAux = new ViajeVO(s);
                if (viajeAux.getCiudadOrigen().equalsIgnoreCase(ciudadOrigen)
                        && viajeAux.getCiudadDestino().equalsIgnoreCase(ciudadDestino)
                        && viajeAux.getHoraSalida().equalsIgnoreCase(horaSalida)) {
                    listaViajes.add(viajeAux);
                }
            }
        } else {
            System.out.println("No existe archivo: " + nombreArchivo + " en el directorio: " + rutaConsulta);
        }
    } catch (IOException ex) {
        System.err.println(ex.toString());
    }
    return listaViajes;
}

From source file:generate.MapGenerateAction.java

@Override
public String execute() {

    String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles";
    try {//from  w  ww  .  j a  va 2  s .c o m
        File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName());
        FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate);
    } catch (Throwable t) {
        System.out.println("E1: " + t.getMessage());
        return ERROR;
    }
    try {
        List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile());
        StringBuilder text = new StringBuilder();
        for (String s : temp_text) {
            text.append(s);
        }
        concept_map.setInput_text(text.toString());
    } catch (IOException e) {
        //e.printStackTrace();
        System.out.println("E2: " + e.getMessage());
        return ERROR;
    }
    String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0];
    temp_filename = temp_filename.trim();

    try {
        String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar "
                + file_path + " " + temp_filename;
        System.out.println(temp);
        File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar");
        JarFile jar = new JarFile(jarfile);
        Manifest manifest = jar.getManifest();
        Attributes attrs = manifest.getMainAttributes();
        String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS);
        System.out.println(mainClassName);
        URL url = new URL("file", null, jarfile.getAbsolutePath());
        ClassLoader cl = new URLClassLoader(new URL[] { url });
        Class mainClass = cl.loadClass(mainClassName);
        Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class });
        String[] args = new String[2];
        args[0] = file_path;
        args[1] = temp_filename;
        System.out.println(args[0]);
        System.out.println(args[1]);
        try {
            mainMethod.invoke(mainClass, new Object[] { args });
        } catch (InvocationTargetException e) {
            System.out.println("This is the exception: " + e.getTargetException().toString());
        }
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException
            | IOException e) {
        System.out.println("E3: " + e.getMessage());
        return ERROR;
    }

    try {
        String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar "
                + file_path + " " + temp_filename;
        System.out.println(temp2);
        File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar");
        JarFile jar = new JarFile(jarfile);
        Manifest manifest = jar.getManifest();
        Attributes attrs = manifest.getMainAttributes();
        String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS);
        System.out.println(mainClassName);
        URL url = new URL("file", null, jarfile.getAbsolutePath());
        ClassLoader cl = new URLClassLoader(new URL[] { url });
        Class mainClass = cl.loadClass(mainClassName);
        Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class });
        String[] args = new String[2];
        args[0] = file_path;
        args[1] = temp_filename;
        mainMethod.invoke(mainClass, new Object[] { args });
    } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException
            | NoSuchMethodException | ClassNotFoundException | IOException e) {
        System.out.println("E4: " + e.getMessage());
        return ERROR;
    }

    String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/"
            + temp_filename + "_OllieOutput.txt\"";
    String[] finalCommand;
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = cmd;
    System.out.println("CMD: " + cmd);
    try {
        //ProcessBuilder builder = new ProcessBuilder(finalCommand);
        //builder.redirectErrorStream(true);
        //Process process = builder.start();
        Process process = Runtime.getRuntime().exec(finalCommand);
        int exitVal = process.waitFor();
        System.out.println("Process exitValue2: " + exitVal);
    } catch (Throwable t) {
        System.out.println("E5: " + t.getMessage());
        return ERROR;
    }

    cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py";
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = cmd;

    try {
        //Process process = Runtime.getRuntime().exec(finalCommand);

        ProcessBuilder builder = new ProcessBuilder(finalCommand);
        // builder.redirectErrorStream(true);
        Process process = builder.start();
        int exitVal = process.waitFor();
        System.out.println("Process exitValue3: " + exitVal);
    } catch (Throwable t) {
        System.out.println("E6: " + t.getMessage());
        return ERROR;
    }

    try {
        List<String> temp_text_1 = FileUtils
                .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json"));
        StringBuilder text_1 = new StringBuilder();
        for (String s : temp_text_1) {
            text_1.append(s);
        }
        concept_map.setOutput_text(text_1.toString());
    } catch (IOException e) {
        System.out.println("E7: " + e.getMessage());
        return ERROR;
    }
    Random rand = new Random();
    int unique_id = rand.nextInt(99999999);
    System.out.println("Going In DB");
    try {
        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("Major");
        DBCollection collection = db.getCollection("ConceptMap");
        BasicDBObject document = new BasicDBObject();
        document.append("InputText", concept_map.getInput_text());
        document.append("OutputText", concept_map.getOutput_text());
        document.append("ChapterName", concept_map.getChapter_name());
        document.append("ChapterNumber", concept_map.getChapter_number());
        document.append("SectionName", concept_map.getSection_name());
        document.append("SectionNumber", concept_map.getSection_number());
        document.append("UniqueID", Integer.toString(unique_id));
        collection.insert(document);
        //collection.save(document);
    } catch (MongoException e) {
        System.out.println("E8: " + e.getMessage());
        return ERROR;
    } catch (UnknownHostException ex) {
        Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("E9");
        return ERROR;
    }
    System.out.println("Out DB");
    return SUCCESS;
}

From source file:com.mirth.connect.server.launcher.MirthLauncher.java

private static void uninstallPendingExtensions() throws Exception {
    File extensionsDir = new File(EXTENSIONS_DIR);
    File uninstallFile = new File(extensionsDir, "uninstall");

    if (uninstallFile.exists()) {
        List<String> extensionPaths = FileUtils.readLines(uninstallFile);

        for (String extensionPath : extensionPaths) {
            File extensionFile = new File(extensionsDir, extensionPath);

            if (extensionFile.exists() && extensionFile.isDirectory()) {
                logger.trace("uninstalling extension: " + extensionFile.getName());
                FileUtils.deleteDirectory(extensionFile);
            }/*from  ww  w . j a v  a2  s. c  om*/
        }

        // delete the uninstall file when we're done
        FileUtils.deleteQuietly(uninstallFile);
    }
}

From source file:de.unidue.ltl.flextag.core.reports.CvAvgAccuracyReport.java

private List<String> getFoldersOfSingleRuns(File attributesTXT) throws Exception {
    List<String> readLines = FileUtils.readLines(attributesTXT);

    int idx = 0;//from   w  w  w . j av a2 s .com
    for (String line : readLines) {
        if (line.startsWith("Subtask")) {
            break;
        }
        idx++;
    }
    String line = readLines.get(idx);
    int start = line.indexOf("[") + 1;
    int end = line.indexOf("]");
    String subTasks = line.substring(start, end);

    String[] tasks = subTasks.split(",");

    List<String> results = new ArrayList<>();

    for (String task : tasks) {
        if (TcTaskTypeUtil.isMachineLearningAdapterTask(getContext().getStorageService(), task.trim())) {
            results.add(task.trim());
        }
    }

    return results;
}

From source file:com.edgenius.wiki.service.impl.TestVolumnPageService.java

@Before
public void setUp() throws IOException {

    System.out.println("Load test file from URL:"
            + this.getClass().getClassLoader().getResource("testcase/pageservice/samplepagecontent.txt"));
    URL samplePage = this.getClass().getClassLoader().getResource("testcase/pageservice/samplepagecontent.txt");
    content = FileUtils.readFileToString(new File(samplePage.getPath()));

    System.out.println("Load test file from URL:"
            + this.getClass().getClassLoader().getResource("testcase/pageservice/spacelist.txt"));
    URL spaceList = this.getClass().getClassLoader().getResource("testcase/pageservice/spacelist.txt");
    spaces = FileUtils.readLines(new File(spaceList.getPath()));

    HttpServletRequest request = new MockHttpServletRequest() {

        public String getRemoteUser() {
            return "admin";
        }// w ww.j  ava  2 s  . c  o m

    };
    ServletUtils.setRequest(request);
    //      MockServletContext servletContext = new MockServletContext();
    //      WebApplicationContext springContext;
    //      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE   , springContext);
    //      ServletUtils.setServletContext(servletContext);

    Authentication authentication = new UsernamePasswordAuthenticationToken("admin", "admin");
    SecurityContextHolder.getContext().setAuthentication(authentication);
    //create spaces
    for (String uname : spaces) {
        Space space = new Space();
        space.setUnixName(uname);
        space.setName("Title:" + uname);
        space.setDescription("Description:" + uname);
        WikiUtil.setTouchedInfo(userReadingService, space);
        try {
            spaceService.createSpace(space);
        } catch (SpaceException e) {
            e.printStackTrace();
            Assert.fail(e.toString());
        }
    }
}

From source file:com.sangupta.shire.domain.RenderableResource.java

/**
 * @return the originalContent//from ww w  .j  a  va2 s  . co  m
 * @throws IOException 
 */
public String getOriginalContent() throws IOException {
    if (originalContent == null) {
        List<String> lines = FileUtils.readLines(this.fileHandle);
        this.originalContent = StringUtils.join(lines.subList(this.matterEndingLine, lines.size()), '\n');
    }

    return originalContent;
}

From source file:it.drwolf.ridire.util.fixingpos.AsyncPosFixer.java

@SuppressWarnings("unchecked")
@Asynchronous/*www.  j  a  va 2 s .  c o  m*/
public void doAsyncFix(PosFixerData posFixerData) {
    StrTokenizer strTokenizer = new StrTokenizer("\t");
    File destDir = new File(posFixerData.getDestDir());
    File reverseDestDir = new File(posFixerData.getReverseDestDir());
    if (!destDir.exists() || !destDir.isDirectory() || !reverseDestDir.exists()
            || !reverseDestDir.isDirectory()) {
        System.err.println("Not valid destination folder.");
        return;
    }
    this.ridireReTagger = new RIDIREReTagger(null);
    try {
        this.entityManager = (EntityManager) Component.getInstance("entityManager");
        this.userTx = (UserTransaction) org.jboss.seam.Component
                .getInstance("org.jboss.seam.transaction.transaction");
        this.userTx.setTransactionTimeout(1000 * 10 * 60);
        if (!this.userTx.isActive()) {
            this.userTx.begin();
        }
        this.entityManager.joinTransaction();
        String treeTaggerBin = this.entityManager
                .find(CommandParameter.class, CommandParameter.TREETAGGER_EXECUTABLE_KEY).getCommandValue();
        this.ridireReTagger.setTreetaggerBin(treeTaggerBin);
        this.entityManager.flush();
        this.entityManager.clear();
        this.userTx.commit();
        List<String> lines = FileUtils.readLines(new File(posFixerData.getFile()));
        int count = 0;
        for (String l : lines) {
            if (l == null || l.trim().length() < 1) {
                continue;
            }
            String digest = l.replaceAll("\\./", "").replaceAll("\\.vrt", "");
            if (!this.userTx.isActive()) {
                this.userTx.begin();
            }
            this.entityManager.joinTransaction();
            List<CrawledResource> crs = this.entityManager
                    .createQuery("from CrawledResource cr where cr.digest=:digest")
                    .setParameter("digest", digest).getResultList();
            if (crs.size() != 1) {
                System.err.println("PosFixer: " + l + " resource not found.");
            } else {
                CrawledResource cr = crs.get(0);
                String origFile = FilenameUtils.getFullPath(cr.getArcFile())
                        .concat(JobMapperMonitor.RESOURCESDIR).concat(digest.concat(".txt"));
                File toBeRetagged = new File(origFile);
                if (toBeRetagged.exists() && toBeRetagged.canRead()) {
                    String retaggedFile = this.ridireReTagger.retagFile(toBeRetagged);
                    int wordsNumber = this.wordCounter.countWordsFromPoSTagResource(new File(retaggedFile));
                    cr.setWordsNumber(wordsNumber);
                    this.entityManager.persist(cr);
                    this.vrtFilesBuilder.createVRTFile(retaggedFile, strTokenizer, cr, destDir);
                    String vrtFileName = destDir + System.getProperty("file.separator") + digest + ".vrt";
                    File vrtFile = new File(vrtFileName);
                    this.vrtFilesBuilder.reverseFile(reverseDestDir, vrtFile);
                }
            }
            this.userTx.commit();
            System.out.println(" Processed " + (++count) + " of " + lines.size());
        }
    } catch (SystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NotSupportedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (RollbackException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (this.userTx != null && this.userTx.isActive()) {
                this.userTx.rollback();
            }
        } catch (IllegalStateException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SystemException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}