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:edu.isi.wings.portal.servlets.HandleUpload.java

/**
 * Handle an HTTP POST request from Plupload.
 *//*from   ww w.ja v  a 2  s  .c o  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    Config config = new Config(request);
    if (!config.checkDomain(request, response))
        return;

    Domain dom = config.getDomain();

    String name = null;
    String id = null;
    String storageDir = dom.getDomainDirectory() + "/";
    int chunk = 0;
    int chunks = 0;
    boolean isComponent = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                try {
                    InputStream input = item.openStream();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String value = Streams.asString(input);
                        if ("name".equals(fieldName))
                            name = value.replaceAll("[^\\w\\.\\-_]+", "_");
                        else if ("id".equals(fieldName))
                            id = value;
                        else if ("type".equals(fieldName)) {
                            if ("data".equals(value))
                                storageDir += dom.getDataLibrary().getStorageDirectory();
                            else if ("component".equals(value)) {
                                storageDir += dom.getConcreteComponentLibrary().getStorageDirectory();
                                isComponent = true;
                            } else {
                                storageDir = System.getProperty("java.io.tmpdir");
                            }
                        } else if ("chunk".equals(fieldName))
                            chunk = Integer.parseInt(value);
                        else if ("chunks".equals(fieldName))
                            chunks = Integer.parseInt(value);
                    } else if (name != null) {
                        File storageDirFile = new File(storageDir);
                        if (!storageDirFile.exists())
                            storageDirFile.mkdirs();
                        File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part");
                        saveUploadFile(input, uploadFile, chunk);
                    }
                } catch (Exception e) {
                    this.printError(out, e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (FileUploadException e1) {
            this.printError(out, e1.getMessage());
            e1.printStackTrace();
        }
    } else {
        this.printError(out, "Not multipart data");
    }

    if (chunks == 0 || chunk == chunks - 1) {
        // Done upload
        File partUpload = new File(storageDir + File.separator + name + ".part");
        File finalUpload = new File(storageDir + File.separator + name);
        partUpload.renameTo(finalUpload);

        String mime = new Tika().detect(finalUpload);
        if (mime.equals("application/x-sh") || mime.startsWith("text/"))
            FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload));

        // Check if this is a zip file and unzip if needed
        String location = finalUpload.getAbsolutePath();
        if (isComponent && mime.equals("application/zip")) {
            String dirname = new URI(id).getFragment();
            location = StorageHandler.unzipFile(finalUpload, dirname, storageDir);
            finalUpload.delete();
        }
        this.printOk(out, location);
    }
}

From source file:gov.nih.nci.firebird.selenium2.pages.sponsor.representative.export.AbstractExportCurationDataTabHelper.java

List<String> getCsvFileContents() throws IOException {
    File csvFile = getTab().clickExportCsv();
    return FileUtils.readLines(csvFile);
}

From source file:com.dubic.dc.dev.assist.services.ModuleService.java

public String processFile(String moduleName, boolean tfw, ModFile mfile) throws IOException {
    if (ModFile.MANUAL.equals(mfile.getAction())) {
        return "Edit manually";
    } else if (ModFile.DELETE.equals(mfile.getAction())) {
        FileUtils.deleteQuietly(new File(mfile.getPath()));
        System.out.println("delete file : " + new File(mfile.getName()));
        return "deleted";
    }/* w  w  w.  j  a va 2 s  .  co m*/

    File f = new File(mfile.getPath());
    Map<String, Object> p = new HashMap<>();
    p.put(serviceKey, moduleName);
    p.put("tfw", tfw);
    String contents = resolveTemplate(p, mfile.getTemplate());

    if (ModFile.REPLACE.equals(mfile.getAction())) {
        FileUtils.write(f, contents);
        System.out.println("Replaced file : " + f.getName());
        return "replaced";
    } else if (ModFile.APPEND.equals(mfile.getAction())) {
        //check if line exists
        if (FileUtils.readFileToString(f).contains(mfile.getChecktext())) {
            System.out.println("EXISTS IN FILE!!! : " + f.getName());
            return "exists";
        }

        List<String> lines = FileUtils.readLines(f);
        boolean started = false;

        int i = 0;
        for (String line : lines) {
            //
            if (mfile.getStartline() != null) {//start line is set
                //                    System.out.println("mfile.getStartline() != null");
                if (line.contains(mfile.getStartline())) {//start line is hit
                    //                        System.out.println("line.equals(mfile.getStartline()");
                    started = true;
                }
                if (started && line.contains(mfile.getEndline())) {//end line hit
                    System.out.println("started && line.equals(mfile.getEndline())");
                    lines.add(i, contents);
                    break;
                }
            } else {//No start line so use end line
                if (mfile.getEndline() == null) {
                    lines.add(contents);
                    break;
                } else if (line.contains(mfile.getEndline())) {//end line hit
                    lines.add(i, contents);
                    break;
                }
            }
            i++;
        }

        //            for (String line : lines) {
        //                System.out.println(line);
        //            }
        FileUtils.writeLines(f, lines);
        System.out.println("Appended to file : " + f.getName());
        return "appended";

    } else if (ModFile.PREPEND.equals(mfile.getAction())) {
        if (FileUtils.readFileToString(f).contains(mfile.getChecktext())) {
            System.out.println("EXISTS IN FILE!!! : " + f.getName());
            return "exists";
        }

        List<String> originalLines = FileUtils.readLines(f);
        originalLines.add(0, contents);
        FileUtils.writeLines(f, originalLines);
        System.out.println("Prepended to file : " + f.getName());
        return "prepended";
    } else if (ModFile.REMOVE.equals(mfile.getAction())) {
        List<String> lines = FileUtils.readLines(f);
        int i = 0;
        for (String line : lines) {
            if (line.contains(contents)) {
                //                    exists?
                if (line.startsWith("//")) {
                    return "exists";
                }
                lines.remove(i);
                lines.add(i, "//".concat(line));
                break;
            }
            i++;
        }
        FileUtils.writeLines(f, lines);
        System.out.println("Commented out from : " + f.getName());
        return "commented";
    } else if (ModFile.CREATE.equals(mfile.getAction())) {
        FileUtils.write(f, contents, "UTF-8");
        System.out.println("Created file : " + f.getName());
        return "created";
    } else {
        System.out.println("No Action");
        return "no action";
    }
}

From source file:form.mydemik.com.DBSetting.java

private void btnSimpanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSimpanActionPerformed
    File file = new File("D:/file.txt");
    if (file.exists()) {

        try {// ww w.ja  v a2s  .  c  o m
            List<String> lines = FileUtils.readLines(file);
            lines.add(1, "Line to add");
            FileUtils.writeLines(file, lines);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(DBSetting.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DBSetting.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        try {
            file.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(DBSetting.class.getName()).log(Level.SEVERE, null, ex);
        }
        DBSetting db = new DBSetting();
        db.setVisible(true);
    }

}

From source file:com.gargoylesoftware.htmlunit.javascript.host.PropertiesTest.java

private static List<String> getProperties(final BrowserVersion browserVersion) throws Exception {
    final URL url = PropertiesTest.class.getClassLoader()
            .getResource("objects/properties." + browserVersion.getNickname() + ".txt");
    return FileUtils.readLines(new File(url.toURI()));
}

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

@Override
public List<TouresBalonOrdenVO> consultaReservas(String ordenId) {
    List<TouresBalonOrdenVO> listaReservasTB = new ArrayList<>();
    String nombreArchivo = Constantes.NAME_RESERVAS + ordenId + Constantes.CSV_FILE;
    try {/*from w  w  w.  j  ava 2s  . co m*/
        File archivoConsulta = FileUtils.getFile(rutaReservas, nombreArchivo);
        if (archivoConsulta != null && archivoConsulta.exists()) {
            List<String> lineasArchivo = FileUtils.readLines(archivoConsulta);
            System.out.println("Archivo encontrado: " + archivoConsulta.getAbsoluteFile());
            for (String s : lineasArchivo) {
                listaReservasTB.add(new TouresBalonOrdenVO(s));
            }
        } else {
            System.out.println("No existe archivo: " + nombreArchivo + " en el directorio: " + rutaReservas);
        }
    } catch (IOException ex) {
        System.err.println(ex.toString());
    }
    return listaReservasTB;
}

From source file:io.github.bunnyblue.droidfix.classcomputer.proguard.MappingMapper.java

public ArrayList<ClassObject> readCacheClasses() {
    ArrayList<ClassObject> cacheClasses = new ArrayList<ClassObject>();
    File cache = new File(Configure.getInstance().getPatchClassMD5());
    try {//from  w  ww .  j a v  a  2  s . co  m
        List<String> caches = FileUtils.readLines(cache);
        for (String string : caches) {
            String[] maps = string.split(" ");
            ClassObject classObject = new ClassObject(maps[1], maps[0]);
            cacheClasses.add(classObject);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return cacheClasses;
}

From source file:ml.shifu.shifu.core.pmml.PMMLVerifySuit.java

private boolean compareScore(File test, File control, String scoreName, String sep, Double errorRange)
        throws Exception {
    List<String> testData = FileUtils.readLines(test);
    List<String> controlData = FileUtils.readLines(control);
    String[] testSchema = testData.get(0).trim().split(sep);
    String[] controlSchema = controlData.get(0).trim().split(sep);

    for (int row = 1; row < controlData.size(); row++) {
        Map<String, Object> ctx = new HashMap<String, Object>();
        Map<String, Object> controlCtx = new HashMap<String, Object>();

        String[] testRowValue = testData.get(row).split(sep, testSchema.length);
        for (int index = 0; index < testSchema.length; index++) {
            ctx.put(testSchema[index], testRowValue[index]);
        }/*from w  w w .j a v a2  s.c o  m*/
        String[] controlRowValue = controlData.get(row).split(sep, controlSchema.length);

        for (int index = 0; index < controlSchema.length; index++) {
            controlCtx.put(controlSchema[index], controlRowValue[index]);
        }

        for (String realScoreName : controlSchema) {
            Double controlScore = Double.valueOf((String) controlCtx.get(realScoreName));
            Double testScore = Double.valueOf((String) ctx.get(realScoreName));
            if (Math.abs(controlScore - testScore) > errorRange) {
                System.out.println(
                        "Row " + row + " - The score doens't match " + controlScore + " vs " + testScore + ".");
                return false;
            }
        }
    }

    return true;
}

From source file:com.przyjaznyplan.utils.CsvConverter.java

private void ifTextGetIt(String value, ContentValues sqlValues) {
    if (value != null && value.endsWith(TXT_EXT)) {
        Collection files = FileUtils.listFiles(new File(rootFolder), new NameFileFilter(value),
                TrueFileFilter.INSTANCE);
        Iterator<File> iterator = files.iterator();
        if (iterator.hasNext()) {
            File f = iterator.next();
            List<String> linesOfText = null;
            try {
                linesOfText = FileUtils.readLines(f);
            } catch (IOException e) {
                Log.e("File IO", e.getMessage());
            }/*from ww  w  . j a  v a2 s.  c  om*/
            StringBuilder builder = new StringBuilder();

            if (linesOfText != null) {
                for (String line : linesOfText) {
                    builder.append(line);
                }
            }

            sqlValues.put(Czynnosc.TEXT, builder.toString());
        }

    } else if (value != null && value.length() > 0) {
        sqlValues.put(Czynnosc.TEXT, value);
    }
}

From source file:es.uvigo.ei.sing.adops.operations.running.tcoffee.TCoffeeDefaultProcessManager.java

protected static int maxSequenceLength(File fastaFile) throws OperationException {
    String flatSequence = "";
    int maxLength = 0;
    try {//from   ww  w . j a  v a  2s  .  c  o  m
        for (String seq : FileUtils.readLines(fastaFile)) {
            if (seq.startsWith(">")) {
                maxLength = max(maxLength, flatSequence.length());

                flatSequence = "";
            } else {
                flatSequence += seq;
            }
        }
    } catch (IOException e) {
        throw new OperationException(null, "Error reading intermediate fasta file", e);
    }

    maxLength = max(maxLength, flatSequence.length());

    return maxLength;
}