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, String encoding, Collection lines, String lineEnding)
        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:org.jahia.services.templates.ModuleBuildHelper.java

private boolean saveFile(InputStream source, File target) throws IOException {
    Charset transCodeTarget = null;
    if (target.getParentFile().getName().equals("resources") && target.getName().endsWith(".properties")) {
        transCodeTarget = Charsets.ISO_8859_1;
    }//from   w  w  w .j  a va2  s  .c  om

    if (!target.exists()) {
        if (!target.getParentFile().exists() && !target.getParentFile().mkdirs()) {
            throw new IOException("Unable to create path for: " + target.getParentFile());
        }
        if (target.getParentFile().isFile()) {
            target.getParentFile().delete();
            target.getParentFile().mkdirs();
        }
        if (transCodeTarget != null) {
            FileUtils.writeLines(target, transCodeTarget.name(),
                    convertToNativeEncoding(IOUtils.readLines(source, Charsets.UTF_8), transCodeTarget), "\n");
        } else {
            FileOutputStream output = FileUtils.openOutputStream(target);
            try {
                IOUtils.copy(source, output);
                output.close();
            } finally {
                IOUtils.closeQuietly(output);
            }
        }

        // Save repository.xml file after first generation
        if (target.getName().equals("repository.xml")) {
            FileUtils.copyFile(target, new File(target.getPath() + ".generated"));
        }

        return true;
    } else {
        List<String> targetContent = FileUtils.readLines(target,
                transCodeTarget != null ? transCodeTarget : Charsets.UTF_8);
        if (!isBinary(targetContent)) {
            File previouslyGenerated = new File(target.getPath() + ".generated");
            List<String> previouslyGeneratedContent = targetContent;
            if (previouslyGenerated.exists()) {
                previouslyGeneratedContent = FileUtils.readLines(previouslyGenerated,
                        transCodeTarget != null ? transCodeTarget : Charsets.UTF_8);
            }
            DiffMatchPatch dmp = new DiffMatchPatch();
            List<String> sourceContent = IOUtils.readLines(source, Charsets.UTF_8);
            if (transCodeTarget != null) {
                sourceContent = convertToNativeEncoding(sourceContent, transCodeTarget);
            }

            LinkedList<DiffMatchPatch.Patch> l = dmp.patch_make(
                    StringUtils.join(previouslyGeneratedContent, "\n"), StringUtils.join(sourceContent, "\n"));

            if (target.getName().equals("repository.xml")) {
                // Keep generated file uptodate
                FileUtils.writeLines(new File(target.getPath() + ".generated"),
                        transCodeTarget != null ? transCodeTarget.name() : "UTF-8", sourceContent);
            }

            if (!l.isEmpty()) {
                Object[] objects = dmp.patch_apply(l, StringUtils.join(targetContent, "\n"));

                for (boolean b : ((boolean[]) objects[1])) {
                    if (!b) {
                        throw new IOException("Cannot apply modification on " + target.getName()
                                + ", check generated file at : " + target.getPath() + ".generated");
                    }
                }
                FileUtils.write(target, (CharSequence) objects[0],
                        transCodeTarget != null ? transCodeTarget.name() : "UTF-8");
                return true;
            }
        } else {
            byte[] sourceArray = IOUtils.toByteArray(source);
            FileInputStream input = new FileInputStream(target);
            FileOutputStream output = null;
            try {
                byte[] targetArray = IOUtils.toByteArray(input);
                if (!Arrays.equals(sourceArray, targetArray)) {
                    output = new FileOutputStream(target);
                    IOUtils.write(sourceArray, output);
                    return true;
                }
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }
        }
    }
    return false;
}

From source file:org.opendatakit.briefcase.ui.CharsetConverterDialog.java

@Override
public void actionPerformed(ActionEvent e) {
    Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
    String actionCommand = e.getActionCommand();

    if (BROWSE_COMMAND.equals(actionCommand)) {
        WrappedFileChooser dlg = new WrappedFileChooser(window,
                new FileChooser(true, "Select the file to convert...", "Select"));
        String path = getFilePath();
        if (path != null && path.trim().length() != 0) {
            dlg.setSelectedFile(new File(path.trim()));
        }//  www  .  j ava  2  s  .  c  om
        int retVal = dlg.showDialog();
        if (retVal == JFileChooser.APPROVE_OPTION) {
            if (dlg.getSelectedFile() != null) {
                String selectedPath = dlg.getSelectedFile().getAbsolutePath();
                tfFile.setText(selectedPath);

                updatePreview();
            }
        }
    } else if (CONVERT_COMMAND.equals(actionCommand)) {
        String filePath = getFilePath();
        if (filePath == null || filePath.trim().length() == 0) {
            return;
        }

        File destinationPath;
        if (cbOverride.isSelected()) {
            destinationPath = new File(filePath);
        } else {
            WrappedFileChooser dlg = new WrappedFileChooser(window,
                    new FileChooser(false, "Select the file to convert to...", "Save"));
            dlg.setSelectedFile(new File(filePath));
            int retVal = dlg.showDialog();
            if (retVal == JFileChooser.APPROVE_OPTION && dlg.getSelectedFile() != null) {
                destinationPath = dlg.getSelectedFile();
            } else {
                return;
            }
        }

        File file = new File(filePath);
        try {
            List<String> lines = FileUtils.readLines(file, getCharsetName());
            FileUtils.writeLines(destinationPath, "UTF-8", lines, LINE_SEPARATOR);

            JOptionPane.showMessageDialog(this, DONE_MESSAGE, DONE_TITLE, JOptionPane.INFORMATION_MESSAGE);

            cancelButton.setText("Close");

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Error converting file...",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else if (CANCEL_COMMAND.equals(actionCommand)) {
        closeDialog();
    }
}

From source file:org.sitoolkit.editor.TextFileEditor.java

void write(Collection<Line> lines, File output) throws IOException {
    List<String> outputLines = new ArrayList<String>();
    for (Line line : lines) {
        if (line.isDeleted()) {
            LOG.trace("removed line:{}", line);
            continue;
        }//from   w  ww. j a v  a  2  s .c o  m
        outputLines.addAll(line.getBefore());
        if (LOG.isTraceEnabled() && !line.getBefore().isEmpty()) {
            LOG.trace("insert before:{}", StringUtils.join(line.getBefore()));
        }

        if (line.getStr() != null) {
            outputLines.add(line.getStr());
            LOG.trace("write line:{}", line);
        }

        outputLines.addAll(line.getAfter());
        if (LOG.isTraceEnabled() && !line.getAfter().isEmpty()) {
            LOG.trace("insert before:{}", StringUtils.join(line.getAfter()));
        }
    }

    LOG.info("?????{}", output.getAbsolutePath());
    FileUtils.writeLines(output, getOutputEncoding(), outputLines, getOutputLineEnding());
}