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:gov.nih.nci.caarray.magetab.splitter.SdrfSplitterTest.java

/**
 * linesToAdd are added in sequential order.  This <em>modifies</em> the lines
 * in place.  So to add 2 lines before the header and 1 after, the keys should be
 * (0, 1, 3), because that will add two lines (moving the header down), then add after
 * the header./*from  w ww . j a  va 2 s.  c  o  m*/
 */
private Function<File, File> getTransform(final SortedMap<Integer, String> linesToAdd) {
    Function<File, File> transform = new Function<File, File>() {
        @Override
        public File apply(File input) {
            try {
                @SuppressWarnings("unchecked")
                List<String> lines = FileUtils.readLines(input);
                for (Integer i : linesToAdd.keySet()) {
                    lines.add(i, linesToAdd.get(i));
                }
                File revisedSdrf = File.createTempFile("test", ".sdrf");
                FileUtils.writeLines(revisedSdrf, lines);
                return revisedSdrf;
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }
    };
    return transform;
}

From source file:com.rowoerowanie.endoexporttokml.ExportKml.java

public void exportToKml(String url, String outFile) {
    try {//w  ww  . jav  a 2 s.  c  om
        this.url = url;
        List<String> kml = new ArrayList<>();
        List<Point> points = new ArrayList<>();
        String lines = IOUtils.toString(loadData(convertUrl(url))).trim();

        JSONObject obj = new JSONObject(lines);

        System.out.println("Trasa: " + obj.get("id"));

        JSONArray arr = obj.getJSONObject("points").getJSONArray("points");

        for (int i = 0; i < arr.length(); i++) {
            JSONObject p = arr.getJSONObject(i);
            /*p.getString("time");
            p.getString("latitude");
            p.getString("longitude");
            p.getString("altitude");
            p.getString("duration");*/

            points.add(new Point(p.getDouble("distance"), p.optDouble("altitude", 0), p.getDouble("longitude"),
                    p.getDouble("latitude")));

        }

        if (!points.isEmpty()) {
            System.out.println("Wygenerowano kml punktw " + points.size());

            kml.add(kmlHead);
            for (Point p : points) {
                kml.add(p.toString());
            }
            kml.add(kmlFoot);
            FileUtils.writeLines(new File(outFile), kml);
        }
    } catch (IOException ex) {
        Logger.getLogger(ExportKml.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(ExportKml.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.isi.wings.portal.servlets.HandleUpload.java

/**
 * Handle an HTTP POST request from Plupload.
 *///  w  ww.  j  a  v  a 2  s  .  co  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:de.unisb.cs.st.javalanche.mutation.run.task.MutationTaskCreator.java

private static File writeListToFile(List<Long> list, int taskId, int totalNumberOfTasks) throws IOException {
    File resultFile = getFileName(taskId, totalNumberOfTasks);
    List<String> lines = new ArrayList<String>();
    for (Long l : list) {
        lines.add(l + "");
    }/*  ww w  .java  2s.com*/
    FileUtils.writeLines(resultFile, lines);
    System.out.println("Task created: " + resultFile.getCanonicalPath());
    return resultFile;
}

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 {//from   ww  w  . java  2  s . co 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.revitasinc.sonar.dp.batch.DefectPredictionSensor.java

/**
 * Writes the supplied set to a file in the current working directory.
 * //from  ww w .  ja va  2s .c om
 * @param set
 */
private void writeToFile(Set<FileScore> set) {
    try {
        FileUtils.writeLines(new File("defect-prediction.txt"), set);
    } catch (IOException e) {
        logger.error("", e);
    }
}

From source file:com.gargoylesoftware.htmlunit.source.BrowserVersionFeaturesSource.java

private void generate(final File dir, final String toSearchFor, final BrowserVersion[] versions)
        throws IOException {
    final File propertiesFolder = new File(root_,
            "src/main/resources/com/gargoylesoftware/htmlunit/javascript/configuration");
    final File featuresFile = new File(root_,
            "src/main/java/com/gargoylesoftware/htmlunit/BrowserVersionFeatures.java");
    for (final File f : dir.listFiles()) {
        if (f.isDirectory()) {
            if (!".svn".equals(f.getName())) {
                generate(f, toSearchFor, versions);
            }/* w w w.j av a2s .c om*/
        } else if (!"JavaScriptConfiguration.java".equals(f.getName())) {
            final List<String> lines = FileUtils.readLines(f);
            boolean modified = false;
            for (int i = 0; i < lines.size(); i++) {
                String line = lines.get(i);
                if (line.contains(toSearchFor)) {
                    line = line.replace(toSearchFor,
                            ".hasFeature(BrowserVersionFeatures." + GENERATED_PREFIX + generatedNext_ + ")");
                    lines.set(i, line);
                    modified = true;

                    final List<String> featuresLines = FileUtils.readLines(featuresFile);
                    featuresLines.add(featuresLines.size() - 4, "");
                    featuresLines.add(featuresLines.size() - 4,
                            "    /** Was originally " + toSearchFor + ". */");
                    featuresLines.add(featuresLines.size() - 4,
                            "    " + GENERATED_PREFIX + generatedNext_ + ",");
                    FileUtils.writeLines(featuresFile, featuresLines);

                    for (final File file : propertiesFolder.listFiles(new FileFilter() {
                        public boolean accept(final File pathname) {
                            for (final BrowserVersion version : versions) {
                                if (pathname.getName().equals(version.getNickname() + ".properties")) {
                                    return true;
                                }
                            }
                            return false;
                        }
                    })) {
                        final List<String> features = FileUtils.readLines(file);
                        features.add(GENERATED_PREFIX + generatedNext_);
                        Collections.sort(features);
                        FileUtils.writeLines(file, features);
                    }
                    generatedNext_++;
                }
            }
            if (modified) {
                FileUtils.writeLines(f, lines);
            }
        }
    }
}

From source file:net.nifheim.beelzebu.coins.common.utils.FileManager.java

private void updateConfig() {
    try {//from ww  w .j  a  v  a2s  . c om
        List<String> lines = FileUtils.readLines(configFile, Charsets.UTF_8);
        int index;
        if (core.getConfig().getInt("version") == 13) {
            core.log("The config file is up to date.");
        } else {
            switch (core.getConfig().getInt("version")) {
            case 9:
                index = lines.indexOf("MySQL:") - 2;
                lines.addAll(index, Arrays.asList(
                        "# Here you can enable Vault to make this plugin manage all the Vault transactions.",
                        "Vault:", "  Use: false", "  # Names used by vault for the currency.", "  Name:",
                        "    Singular: 'Coin'", "    Plural: 'Coins'", ""));
                index = lines.indexOf("version: 9");
                lines.set(index, "version: 10");
                core.log("Configuraton file updated to v10");
                break;
            case 10:
                index = lines.indexOf("    Close:") + 1;
                lines.addAll(index, Arrays.asList(
                        "      # To see all possible values check https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html",
                        "      Material: REDSTONE_BLOCK", "      Name: '&c&lClose'", "      Lore:",
                        "      - ''", "      - '&7Click me to close this gui'"));
                index = lines.indexOf("version: 10");
                lines.set(index, "version: 11");
                core.log("Configuraton file updated to v11");
                break;
            case 11:
                index = lines.indexOf("  Executor Sign:") + 5;
                lines.addAll(index, Arrays.asList(
                        "  # If you want the users to be created when they join to the server, enable this,",
                        "  # otherwise the players will be created when his coins are modified or consulted",
                        "  # to the database for the first time (recommended for big servers).",
                        "  Create Join: false"));
                index = lines.indexOf("version: 11");
                lines.set(index, "version: 12");
                core.log("Configuration file updated to v12");
                break;
            case 12:
                index = lines.indexOf("version: 12");
                lines.set(index, "version: 13");
                core.log("Configuration file updated to v13");
                break;
            default:
                core.log(
                        "Seems that you hava a too old version of the config or you canged this to another number >:(");
                core.log(
                        "We can't update it, if is a old version you should try to update it slow and not jump from a version to another, keep in mind that we keep track of the last 3 versions of the config to update.");
                break;
            }
        }
        FileUtils.writeLines(configFile, lines);
        core.getConfig().reload();
    } catch (IOException ex) {
        core.log("An unexpected error occurred while updating the config file.");
        core.debug(ex.getMessage());
    }
}

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

@Test
public void testEscapePropertiesConfiguration() throws Exception {
    File confFile = temp.newFile("props.cfg");
    FileUtils.writeLines(confFile,
            Arrays.asList("input.file.name=RESOLVED", "-1=ERR", "*=ERR2", "1-3=ERR3", ">1=ERR4",
                    "1,2,3=1\\,2\\,3", "escape=-escape $${input.file.name}",
                    "resolve=-resolve ${input.file.name}[0]"));
    PropertiesConfiguration conf = new PropertiesConfiguration(confFile);
    assertEquals("ERR", conf.getString("-1"));
    assertEquals("ERR2", conf.getString("*"));
    assertEquals("ERR3", conf.getString("1-3"));
    assertEquals("ERR4", conf.getString(">1"));
    assertEquals("1,2,3", conf.getString("1,2,3"));
    assertEquals("-escape ${input.file.name}", conf.getString("escape"));
    assertEquals("-resolve RESOLVED[0]", conf.getString("resolve"));
}

From source file:automaticdatabaseupdate.FileHandler.java

public static void WriteTraceMessagesToFile(File file, ArrayList<TraceMessage> listMessages) {
    try {/*w  ww . j  a  va 2  s.com*/
        FileUtils.writeLines(file, listMessages);
    } catch (IOException ex) {
        Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}