Example usage for java.io FileWriter write

List of usage examples for java.io FileWriter write

Introduction

In this page you can find the example usage for java.io FileWriter write.

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.github.aneveux.docukes.generators.MarkdownGenerator.java

/**
 * Creates a markdown file in the target repository containing some
 * documentation generated from the specified Java class
 * // ww  w  .j  a v a2 s . c om
 * @param clazz
 *            a Java class containing some cukes annotations
 * @param methods
 *            the methods of the Java class which are actually annotated
 *            with Cukes
 * @param withDate
 *            defines if the markdown file should contain the time on which
 *            generation has been performed
 */
public void write(JavaClassSource clazz, List<MethodSource<JavaClassSource>> methods, boolean withDate) {
    final File file = new File(target.getPath() + "/" + clazz.getName() + ".md");
    try {
        final FileWriter writer = new FileWriter(file);
        writer.write(generateContent(clazz, methods, withDate));
        writer.flush();
        writer.close();
    } catch (final IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:TestGetXMLClient.java

public void testXML() throws Exception {
    Collection<Class> classList = getClasses();
    String serverUrl = "@SERVER_URL@";
    for (Class klass : classList) {
        System.out.println("Searching for " + klass.getName());
        try {//www . j a  v a  2s.  co  m
            String searchUrl = serverUrl + "/GetXML?query=" + klass.getName() + "&" + klass.getName();
            URL url = new URL(searchUrl);
            URLConnection conn = url.openConnection();

            //Uncomment following two lines for secured system and provide proper username and password
            //String base64 = "userId" + ":" + "password";
            //conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

            File myFile = new File("./output/" + klass.getName() + "_test-getxml.xml");

            FileWriter myWriter = new FileWriter(myFile);
            DataInputStream dis = new DataInputStream(conn.getInputStream());

            String s = null;
            while ((s = dis.readLine()) != null)
                myWriter.write(s);

            myWriter.close();
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
            e.printStackTrace();
        }
        break;
    }
}

From source file:com.greenpepper.maven.runner.resolver.CoordinatesResolver.java

private File createTemporaryPomFile(String groupId, String artifactId, String version) throws IOException {
    File tempPomFile = File.createTempFile("pom-", ".xml");

    FileWriter pomWriter = null;
    try {// w  w  w .  j ava 2 s .  c  o m
        pomWriter = new FileWriter(tempPomFile);
        pomWriter.write(toPOM(groupId, artifactId, version));
    } finally {
        tempPomFile.deleteOnExit();
        if (pomWriter != null) {
            pomWriter.close();
        }
    }

    return tempPomFile;
}

From source file:com.roncoo.pay.reconciliation.fileDown.impl.AlipayFileDown.java

/**
 * ?/*from  w  ww .  ja  va 2s.c  o  m*/
 * 
 * @param bill_date
 *            ?
 * @param stringResult
 *            
 * @param dir
 *            ?
 * @return
 * @throws IOException
 */
private File createFile(String bill_date, String stringResult, String dir) throws IOException {

    // ?
    // String dir = "/home/roncoo/app/accountcheck/billfile/alipay";
    File file = new File(dir, bill_date + "_" + ".xml");
    int index = 1;
    // ??
    while (file.exists()) {
        file = new File(dir, bill_date + "_" + index + ".xml");
        index++;
    }

    // ?,?
    if (!file.getParentFile().exists()) {
        if (!file.getParentFile().mkdirs()) {
            // 
            throw new IOException("(), filepath: " + file.getAbsolutePath());
        }
    }
    // ??
    if (!file.exists()) {
        if (!file.createNewFile()) {
            // 
            throw new IOException(", filepath: " + file.getAbsolutePath());
        }
    }

    try {
        // ??
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(stringResult);
        fileWriter.close(); // ??

    } catch (IOException e) {
        LOG.info("??:" + e);
    }

    return file;
}

From source file:net.sf.ginp.commands.UploadConfig.java

/**
 *  Handle admin request to upload an new configuration file.
 *
 * @param  model   Description of the Parameter
 * @param  params  Description of the Parameter
 *//*from   w w  w . j  ava  2  s .  co m*/
public final void action(final GinpModel model, final Vector params) {
    // Check we do not have a state of bad config.
    if (Configuration.configOK()) {
        return;
    }

    File confFile = new File(Configuration.getConfigfilelocation());

    // check that file is not there.
    if (confFile.exists()) {
        log.error("Config File there but NOT OK.  Fix it or remove it.");

        return;
    }

    for (int i = 0; i < params.size(); i++) {
        CommandParameter param = (CommandParameter) params.get(i);
        log.debug(param.getName() + " = " + param.getValue());

        if (param.getName().equals("configfile")) {
            try {
                InputStream is = (InputStream) param.getObject();
                InputStreamReader isr = new InputStreamReader(is);
                FileWriter fw = new FileWriter(confFile);
                int b = isr.read();

                while (b != -1) {
                    fw.write(b);
                    b = isr.read();
                }

                fw.flush();
            } catch (Exception ex) {
                log.error("Error writing Config File from upload stream.", ex);
            }
        }
    }

    if (Configuration.configOK()) {
        log.info("Uploaded valid Config");
    }

    model.setUserName("admin");
    model.setCurrentPage("setup2.jsp");
}

From source file:de.joinout.criztovyl.tools.json.JSONFile.java

/**
 * Writes the JSON data to the file.//w ww .  j a va 2  s.c o  m
 */
public void write() {

    try {
        //Create file if not exists
        path.touch();

        //Create writer
        final FileWriter fw = new FileWriter(path.getFile());

        //Write
        fw.write(data);

        //Flush 'n' close
        fw.flush();
        fw.close();
    } catch (final IOException e) {
        logger.catching(e);
    }

}

From source file:au.edu.unsw.cse.soc.federatedcloud.curator.CuratorAPI.java

/**
 * This is a temporary method until a proper DB is figured out.
 * @param description/*from  w  ww.j a v  a 2s .  c  om*/
 */
private void persistDescription(CloudResourceDescription description) throws Exception {
    //convert the description to json object
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(description);

    try {
        FileWriter writer = new FileWriter(KB_LOCATION + description.getName() + ".json");
        writer.write(json);
        writer.close();
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    }

}

From source file:com.ExtendedAlpha.SWI.Data.DataSeparator.java

public void writeData(final File file, final String data) {
    plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
        @Override/*from  w w  w  .j ava 2 s.com*/
        public void run() {
            FileWriter writer = null;
            try {
                writer = new FileWriter(file);
                writer.write(data);
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    });
}

From source file:com.mellanox.r4h.MiniDFSClusterManager.java

/**
 * Starts DFS as specified in member-variable options. Also writes out
 * configuration and details, if requested.
 *//*from ww  w .java2  s . co m*/
public void start() throws IOException, FileNotFoundException {
    dfs = new MiniDFSCluster.Builder(conf).nameNodePort(nameNodePort).numDataNodes(numDataNodes)
            .startupOption(dfsOpts).format(format).build();
    dfs.waitActive();

    LOG.info("Started MiniDFSCluster -- namenode on port " + dfs.getNameNodePort());

    if (writeConfig != null) {
        FileOutputStream fos = new FileOutputStream(new File(writeConfig));
        conf.writeXml(fos);
        fos.close();
    }

    if (writeDetails != null) {
        Map<String, Object> map = new TreeMap<String, Object>();
        if (dfs != null) {
            map.put("namenode_port", dfs.getNameNodePort());
        }

        FileWriter fw = new FileWriter(new File(writeDetails));
        fw.write(new JSON().toJSON(map));
        fw.close();
    }
}

From source file:co.edu.uniandes.bigdata.ProyectoBigData.logica.FeedsReader.java

private List<Feed> filterXquery(String category, String source, String property, String filterText,
        boolean excludes) throws IOException, XQException {

    String fileName = getXMLName(category, source);
    String xmlPath = getXMLPath(fileName);

    String exclude_xquery_strg_ini = "";
    String exclude_xquery_strg_end = "";
    if (excludes) {
        exclude_xquery_strg_ini = "not(";
        exclude_xquery_strg_end = ")";
    }/*from w  ww.ja va  2  s  .c om*/

    String xq_query = "";

    if (property.equals("title_description")) { // create xQuery looking for title and description
        xq_query += "for $item in doc(\"" + xmlPath + "\")/rss/channel/item\n";
        xq_query += "where " + exclude_xquery_strg_ini + "contains(upper-case($item/title),upper-case(\""
                + filterText + "\"))" + " or contains(upper-case($item/description),upper-case(\"" + filterText
                + "\"))" + exclude_xquery_strg_end + "\n";
        xq_query += "return concat($item/data(title), '|', $item/data(pubDate), '|', $item/data(link))\n\n";
    } else { // create xQuery for property
        xq_query += "for $item in doc(\"" + xmlPath + "\")/rss/channel/item\n";
        xq_query += "where " + exclude_xquery_strg_ini + "contains(upper-case($item/title),upper-case(\""
                + filterText + "\"))" + exclude_xquery_strg_end + "\n";
        xq_query += "return concat($item/data(title), '|', $item/data(pubDate), '|', $item/data(link))\n\n";
    }

    // create xq file for evidence
    File file = new File(getXQPath(fileName));
    FileWriter out = new FileWriter(file);
    out.write(xq_query);
    out.close();

    // executes XQuery
    XQDataSource ds = new SaxonXQDataSource();
    XQConnection conn = ds.getConnection();
    XQPreparedExpression exp = conn.prepareExpression(xq_query);
    XQResultSequence result = exp.executeQuery();

    // creates feeds List splitting values from xq result
    List<Feed> feeds = new ArrayList<>();

    while (result.next()) {
        String feedText = result.getItemAsString(null);
        String[] feed = feedText.split("\\|");
        String title = feed[0], pubDate = feed[1], urlLink = feed[2];
        feeds.add(new Feed(category, source, cleanTitle(title), urlLink, pubDate));
    }

    return feeds;

}