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

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

Introduction

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

Prototype

public static void writeLines(File file, Collection lines) throws IOException 

Source Link

Document

Writes the toString() value of each item in a collection to the specified File line by line.

Usage

From source file:edu.isi.wings.portal.classes.StorageHandler.java

public static String unzipFile(File f, String todirname, String toDirectory) {
    File todir = new File(toDirectory);
    if (!todir.exists())
        todir.mkdirs();//from   ww  w.j  ava 2  s.  com

    try {
        // Check if the zip file contains only one directory
        ZipFile zfile = new ZipFile(f);
        String topDir = null;
        boolean isOneDir = true;
        for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) {
            ZipEntry ze = e.nextElement();
            String name = ze.getName().replaceAll("/.+$", "");
            name = name.replaceAll("/$", "");
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (name.equals("__MACOSX"))
                continue;

            if (topDir == null)
                topDir = name;
            else if (!topDir.equals(name)) {
                isOneDir = false;
                break;
            }
        }
        zfile.close();

        // Delete existing directory (if any)
        FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname));

        // Unzip file(s) into toDirectory/todirname
        ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (fileName.startsWith("__MACOSX")) {
                ze = zis.getNextEntry();
                continue;
            }

            // Get relative file path translated to 'todirname'
            if (isOneDir)
                fileName = fileName.replaceFirst(topDir, todirname);
            else
                fileName = todirname + File.separator + fileName;

            // Create directories
            File newFile = new File(toDirectory + File.separator + fileName);
            if (ze.isDirectory())
                newFile.mkdirs();
            else
                newFile.getParentFile().mkdirs();

            try {
                // Copy file
                FileOutputStream fos = new FileOutputStream(newFile);
                IOUtils.copy(zis, fos);
                fos.close();

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

                // Set all files as executable for now
                newFile.setExecutable(true);
            } catch (FileNotFoundException fe) {
                // Silently ignore
                //fe.printStackTrace();
            }
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();

        return toDirectory + File.separator + todirname;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:gov.nih.nci.caarray.magetab.splitter.SdrfSplitterTest.java

/**
 * Checks that sdrf files that should have failed validation
 * @throws IOException/*from w  w w . j a  v a 2 s .  c o  m*/
 */
@Test(expected = IllegalArgumentException.class)
public void onlyComments() throws IOException {
    List<String> content = Lists.newArrayList("# comment", "", "# another comment");
    File file = File.createTempFile("test", ".sdrf");
    FileUtils.writeLines(file, content);
    FileRef fileRef = new JavaIOFileRef(file);
    new SdrfSplitter(fileRef);
    fail("Should throw IllegalArgumentException");
}

From source file:com.sketchy.server.action.ManageNetworkSettings.java

public void updateNetworkInfo(NetworkInfo networkInfo) throws Exception {

    List<String> lines = FileUtils.readLines(WPA_SUPPLICANT_FILE);

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

    for (String line : lines) {

        if (StringUtils.containsIgnoreCase(line, "ssid=\"")) {
            line = "\tssid=\"" + networkInfo.ssid + "\"";
        } else if (StringUtils.containsIgnoreCase(line, "psk=\"")) {
            line = "\tpsk=\"" + networkInfo.password + "\"";
        }//from   www .  ja  v  a  2s  . com
        newLines.add(line);
    }

    FileUtils.writeLines(WPA_SUPPLICANT_FILE, newLines);
}

From source file:eu.delving.sip.files.StorageHelper.java

static void writeFacts(File file, Map<String, String> facts) throws IOException {
    List<String> lines = new ArrayList<String>();
    lines.add("#SIPCreator - facts");
    for (Map.Entry<String, String> entry : facts.entrySet()) {
        lines.add(String.format("%s=%s", entry.getKey(), entry.getValue()));
    }/*from   w  w w . ja v a 2s.  c o m*/
    FileUtils.writeLines(file, lines);
}

From source file:ch.bender.evacuate.EvacuateMainTest.java

/**
 * This method is executed just before each test method
 * /*from w w w  . j a va 2s . co m*/
 * @throws Throwable
 *         On any problem (test method will not be executed)
 */
@Before
public void setUp() throws Throwable {
    myLog.debug("entering");
    try {
        if (Files.exists(Testconstants.ROOT_DIR)) {
            Helper.deleteDirRecursive(Testconstants.ROOT_DIR);
        }

        Files.createDirectory(Testconstants.ROOT_DIR);
        FSOBJECTS.DIR1.setFsObject(Testconstants.createNewFolder(Testconstants.ROOT_DIR, "existingDir1"));
        FSOBJECTS.DIR2.setFsObject(Testconstants.createNewFolder(Testconstants.ROOT_DIR, "existingDir2"));
        FSOBJECTS.DIR3.setFsObject(Testconstants.createNewFolder(Testconstants.ROOT_DIR, "existingDir3"));
        FSOBJECTS.FILE1.setFsObject(Testconstants.createNewFile(Testconstants.ROOT_DIR, "existingFile1.txt"));
        FSOBJECTS.FILE2.setFsObject(Testconstants.createNewFile(Testconstants.ROOT_DIR, "existingFile2.txt"));
        FSOBJECTS.FILE3.setFsObject(Testconstants.createNewFile(Testconstants.ROOT_DIR, "existingFile3.txt"));
        FSOBJECTS.NOT1.setFsObject(Paths.get(Testconstants.ROOT_DIR.toString(), "notExisting1"));
        FSOBJECTS.NOT2.setFsObject(Paths.get(Testconstants.ROOT_DIR.toString(), "notExisting2"));
        FSOBJECTS.NOT3.setFsObject(Paths.get(Testconstants.ROOT_DIR.toString(), "notExisting3"));

        Files.deleteIfExists(Paths.get(EXCLUDE_FILE_NAME));
        myExcludeFile = Testconstants.createNewFile(Paths.get("."), EXCLUDE_FILE_NAME);
        FileUtils.writeLines(myExcludeFile.toFile(), Arrays.asList(new String[] { EXCLUDE_VALUE }));
    } catch (Throwable t) {
        myLog.error("Throwable caught in setup", t);
        throw t;
    }
}

From source file:es.uvigo.ei.sing.adops.datatypes.BatchProjectOutput.java

private void store() throws IOException {
    synchronized (this.projects) {
        final File summary = new File(this.project.getFolder(), BatchProjectOutput.STATUS_FILE);
        final List<String> lines = new LinkedList<>();

        final File[] fastaFiles = this.project.getFastaFiles();
        for (int i = 0; i < fastaFiles.length; i++) {
            final File projectDir = this.project.getProjectDirectories()[i];
            final Project project = this.projects.get(fastaFiles[i]);

            if (project == null) {
                lines.add(projectDir.getName() + "=Unexecuted");
            } else if (this.projectOutputs.containsKey(project)) {
                lines.add(projectDir.getName() + "=Executed");
            } else if (this.projectErrors.containsKey(project)) {
                lines.add(/*w  ww  .j a va  2  s.c om*/
                        projectDir.getName() + "=Error[" + this.projectErrors.get(project).getMessage() + "]");
            } else {
                lines.add(projectDir.getName() + "=Unexecuted");
            }
        }

        FileUtils.writeLines(summary, lines);
    }
}

From source file:com.mycompany.crawlertest.GrabManager.java

public void write(String path) throws IOException {
    FileUtils.writeLines(new File(path), masterList);
}

From source file:cz.cas.lib.proarc.common.process.GenericExternalProcessTest.java

@Test
public void testIMConvertFailure() throws Exception {
    String imageMagicExec = "/usr/bin/convert";
    Assume.assumeTrue(new File(imageMagicExec).exists());
    File confFile = temp.newFile("props.cfg");
    File root = temp.getRoot();//from  w  w  w. ja  v a  2s . c o  m
    File pdfa = new File(root, "pdfa_test.pdf");
    FileUtils.writeLines(confFile,
            Arrays.asList("input.file.name=RESOLVED", "exec=" + imageMagicExec, "arg=-thumbnail", "arg=120x128",
                    "arg=$${input.file}[0]", "arg=-flatten", "arg=$${input.folder}/$${input.file.name}.jpg",
                    "onExits=0", "onExit.0.param.output.file=$${input.folder}/$${input.file.name}.jpg",
                    "id=test"));
    PropertiesConfiguration conf = new PropertiesConfiguration(confFile);
    GenericExternalProcess gep = new GenericExternalProcess(conf);
    gep.addInputFile(pdfa);
    gep.run();
    //        System.out.printf("#exit: %s, out: %s\nresults: %s\n",
    //                gep.getExitCode(), gep.getFullOutput(), gep.getResultParameters());
    assertEquals("exit code", 1, gep.getExitCode());
    String outputPath = gep.getResultParameters().get("test.param." + GenericExternalProcess.DST_PATH);
    assertNull(outputPath);
}

From source file:com.roquahacks.semafor4j.FrameNetService.java

public void createAnnotationFile(List<String> sentences) {
    try {//from   w w w  .ja  v  a2 s .  c o  m
        final String file = FrameNetOptions.ABS_PATH_FNDATA + FrameNetOptions.FN_FILE_NAME;
        FileUtils.writeLines(new File(file), sentences);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

private void replaceOWithGaps(File inputFile) throws OperationException {
    if (this.getLogger() != null)
        this.getLogger().info("Command: Replacing o with gaps in: " + inputFile.getAbsolutePath());
    try {/*from   ww w . j a  v a  2s .c  o m*/
        FileUtils.writeLines(inputFile,
                Utils.replaceNames(Collections.singletonMap("o", "-"), FileUtils.readLines(inputFile)));
    } catch (IOException ioe) {
        throw new OperationException(ioe);
    }
}