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.wellcomer.query3.core.Autocomplete.java

/**
    ?.   ?,  TreeSet ?  ? ?. ? TreeSet   .
        //from www  .ja  v  a  2s. com
    @param queryList ?? ?.
    @param scanModifiedOnly ?   ?.
    @param mergePrevious ?? ?  ??  .
*/
public void autolearn(QueryList queryList, boolean scanModifiedOnly, boolean mergePrevious) throws IOException {

    FileTime timestamp;
    long modifiedSince = 0;
    Path timestampFilePath = Paths.get(filePath, ".timestamp");

    if (scanModifiedOnly) { //   
        try { //  ?   ? ?
            timestamp = Files.getLastModifiedTime(timestampFilePath);
            modifiedSince = timestamp.toMillis();
        } catch (IOException e) { //    ?    ? 
            Files.createFile(timestampFilePath);
        }
    }

    HashMap<String, TreeSet<String>> fields = new HashMap<>(); //  - ? ?,  -  ? 
    Iterator<Query> queryIterator = queryList.iterator(modifiedSince); // ? ?? ? ?  ?

    String k, v;

    while (queryIterator.hasNext()) {

        Query query = queryIterator.next();

        for (Map.Entry<String, String> entry : query.entrySet()) {

            k = entry.getKey().toLowerCase();
            v = entry.getValue().trim();

            if (v.length() < 2)
                continue;

            if (!fields.containsKey(k)) {

                TreeSet<String> treeSet = new TreeSet<>();

                try {
                    if (mergePrevious) { // ? ?  
                        List<String> lines = Files.readAllLines(Paths.get(filePath, k), charset);
                        treeSet.addAll(lines);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                fields.put(k, treeSet);
            }
            TreeSet<String> treeSet = fields.get(k);
            treeSet.add(v);
        }
    }

    for (Map.Entry<String, TreeSet<String>> entry : fields.entrySet()) {

        k = entry.getKey();
        ArrayList<String> lines = new ArrayList<>(fields.get(k));

        FileWriter fileWriter = new FileWriter(Paths.get(filePath, k).toString());
        fileWriter.write(StringUtils.join(lines, System.getProperty("line.separator")));
        fileWriter.flush();
        fileWriter.close();
    }

    try {
        Files.setLastModifiedTime(timestampFilePath, FileTime.fromMillis(System.currentTimeMillis()));
    } catch (IOException e) {
        if (e.getClass().getSimpleName().equals("NoSuchFileException"))
            Files.createFile(timestampFilePath);
        e.printStackTrace();
    }
}

From source file:com.xpn.xwiki.plugin.svg.SVGPlugin.java

public byte[] getSVGImage(int hashCode, String content, String extension, int height, int width)
        throws IOException, SVGConverterException {
    File dfile = getTempFile(hashCode, "svg");
    if (!dfile.exists()) {
        FileWriter fwriter = new FileWriter(dfile);
        fwriter.write(content);
        fwriter.flush();/*from  w w w .j  a  va2 s  .  c om*/
        fwriter.close();
    }

    File ofile = getTempFile(hashCode, extension);
    // TODO implement conversion HERE

    SVGConverter conv = new SVGConverter();
    // TODO PNG ONLY
    conv.setDestinationType(DestinationType.PNG);
    conv.setDst(ofile);
    conv.setHeight(height);
    conv.setWidth(width);
    String[] sources = { dfile.getAbsolutePath() };
    conv.setSources(sources);
    conv.execute();

    FileInputStream fis = new FileInputStream(ofile);
    byte[] result = new byte[(int) ofile.length()];
    try {
        fis.read(result);
    } finally {
        IOUtils.closeQuietly(fis);
    }

    return result;
}

From source file:com.thoughtworks.go.domain.builder.FetchPluggableArtifactBuilderTest.java

@Test
public void shouldRegisterAndDeRegisterArtifactRequestProcessBeforeAndAfterPublishingPluggableArtifact()
        throws IOException {
    final FetchPluggableArtifactBuilder builder = new FetchPluggableArtifactBuilder(new RunIfConfigs(),
            new NullBuilder(), "", jobIdentifier, artifactStore, fetchPluggableArtifactTask.getConfiguration(),
            fetchPluggableArtifactTask.getArtifactId(), sourceOnServer, metadataDest, checksumFileHandler);
    final Map<String, Object> metadata = Collections.singletonMap("Version", "10.12.0");

    final FileWriter fileWriter = new FileWriter(metadataDest);
    fileWriter.write(new Gson().toJson(metadata));
    fileWriter.close();//w w  w. j a  va 2s .c  o  m

    builder.build(publisher, new EnvironmentVariableContext(), null, artifactExtension, registry, "utf-8");

    InOrder inOrder = inOrder(registry, artifactExtension);
    inOrder.verify(registry, times(1)).registerProcessorFor(eq(CONSOLE_LOG.requestName()),
            ArgumentMatchers.any(ArtifactRequestProcessor.class));
    inOrder.verify(artifactExtension).fetchArtifact(eq(PLUGIN_ID), eq(artifactStore),
            eq(fetchPluggableArtifactTask.getConfiguration()), any(), eq(metadataDest.getParent()));
    inOrder.verify(registry, times(1)).removeProcessorFor(CONSOLE_LOG.requestName());
}

From source file:cz.msebera.unbound.dns.fragments.MainLogFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case MENU_EMPTY:
        try {//w w w. ja v  a  2 s .com
            FileWriter fw = new FileWriter(
                    new File(getActivity().getFilesDir(), getString(R.string.path_mainlog)), false);
            fw.write("");
            fw.close();
            Toast.makeText(getActivity(), R.string.configuration_saved, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Log.e(TAG, getString(R.string.error_cannot_write_unbound_conf), e);
        }
    case MENU_CLEAR:
        mTextArea.setText("");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.krikelin.spotifysource.AppInstaller.java

protected void copyFile(String src, String dest) throws IOException {
    File inputFile = new File(src);
    File outputFile = new File(dest);

    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;//from www . ja v a  2  s  .co m

    while ((c = in.read()) != -1)
        out.write(c);

    in.close();
    out.close();
}

From source file:com.cyberway.issue.crawler.scope.SeedCachingScopeTest.java

public void testNoScheme() throws IOException {
    final String NOSCHEME = "x.y.z";
    FileWriter fw = new FileWriter(this.seedsfile, true);
    // Write to new (last) line the URL.
    fw.write("\n");
    fw.write(NOSCHEME);/*w ww  . j  a  v a 2s.  co m*/
    fw.flush();
    fw.close();
    boolean found = false;
    SeedCachingScope sl = new UnitTestSeedCachingScope(seedsfile);
    for (Iterator i = sl.seedsIterator(); i.hasNext();) {
        UURI uuri = (UURI) i.next();
        if (uuri.getHost() == null) {
            continue;
        }
        if (uuri.getHost().equals(NOSCHEME)) {
            found = true;
            break;
        }
    }
    assertTrue("Did not find " + NOSCHEME, found);
}

From source file:com.provenance.cloudprovenance.policyhandler.ws.support.PolicyRequestProcessor.java

private void storeRequest(String requestId, String requestContent, HttpServletRequest request)
        throws IOException {

    File requestFile = new File(
            request.getRealPath(cProvlRequestDirectoryPath) + "/request" + requestId + "-cprovl.xml");

    logger.info("File URI: " + requestFile.getAbsolutePath());

    requestFile.createNewFile();//from   w  w w .  j  a v a  2 s  .c om

    FileWriter fWritter = new FileWriter(requestFile);
    fWritter.write(requestContent);
    fWritter.close();
}

From source file:jsfml1.NewJFrame.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    try {//from   w  w w  . jav  a2  s. c  o  m
        // TODO add your handling code here:

        File f = new File(date + ".html");
        FileWriter fw = new FileWriter(f);
        fw.write("<!--" + date + " " + ose + " " + username + " is good ! -->");
        fw.write("<head>");
        fw.write("<style>");
        fw.write("body {");
        fw.write("background: #121212;");
        fw.write("color: white;");
        fw.write("text-align: center;");
        fw.write("}");
        fw.write("</style>");
        fw.write("<title>Listening on</title>");
        fw.write("</head>");
        fw.write("<body>");
        fw.write("Listening on: <br/><br/>");
        fw.write("<audio controls=\"controls\"> <source src=\"" + date + ".wav\"> </audio>");
        fw.write("</body>");
        fw.close();

        JOptionPane jop = new JOptionPane();
        jButton4.setText("Uploaded fine !");
        FTPClient ftp = new FTPClient();
        ftp.connect("ftp.cluster1.easy-hebergement.net", 21);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.user("toNSite");
        ftp.pass("tonMotDePasse");
        InputStream is0 = new FileInputStream(date + ".html");
        InputStream is = new FileInputStream(date + ".wav");
        ftp.storeFile("/uploads/" + date + ".html", is0);
        ftp.storeFile("/uploads/" + date + ".wav", is);
        is.close();
        Desktop.getDesktop().browse(new URI("http://focaliser.fr/uploads/" + date + ".html"));
    } catch (MalformedURLException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (URISyntaxException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:controllers.ControllerServlet.java

private void save() {
    String filePath;//from   ww w.ja  v  a  2  s .co m
    filePath = "/Users/ivan/Desktop/ufns.json";
    JSONObject obj = UFNS.getInstance().getJSONObject();
    try {

        FileWriter file = new FileWriter(filePath);
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

From source file:net.semanticmetadata.lire.solr.AddImagesFromDataFile.java

public void createXml(File outDirectory, File inputFile)
        throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    InputStream in = new FileInputStream(inputFile);
    byte[] tempInt = new byte[4];
    int tmp, tmpFeature;
    int count = 0;
    byte[] temp = new byte[10 * 1024 * 1024];
    // read file hashFunctionsFileName length:
    FileWriter out = new FileWriter(outDirectory.getPath() + "/data_001.xml", false);
    int fileCount = 1;
    out.write("<add>\n");
    while ((tmp = in.read(tempInt, 0, 4)) > 0) {
        tmp = SerializationUtils.toInt(tempInt);
        // read file name:
        in.read(temp, 0, tmp);/* www .  j  a  v  a2s. c  om*/
        String filename = new String(temp, 0, tmp);
        // normalize Filename to full path.
        File file = new File(filename);
        out.write("\t<doc>\n");
        // id and file name ...
        out.write("\t\t<field name=\"id\">");
        out.write(file.getCanonicalPath().replace("D:\\DataSets\\WIPO-", "").replace('\\', '/'));
        out.write("</field>\n");
        out.write("\t\t<field name=\"title\">");
        out.write(file.getName());
        out.write("</field>\n");
        //            System.out.print(filename);
        while ((tmpFeature = in.read()) < 255) {
            //                System.out.print(", " + tmpFeature);
            LireFeature f = (LireFeature) Class.forName(Extractor.features[tmpFeature]).newInstance();
            // byte[] length ...
            in.read(tempInt, 0, 4);
            tmp = SerializationUtils.toInt(tempInt);
            // read feature byte[]
            int read = in.read(temp, 0, tmp);
            if (read != tmp)
                System.err.println("!!!");
            f.setByteArrayRepresentation(temp, 0, tmp);
            addToDocument(f, out, file);
            //                d.add(new StoredField(Extractor.featureFieldNames[tmpFeature], f.getByteArrayRepresentation()));
        }
        out.write("\t</doc>\n");
        count++;
        if (count % 100000 == 0) {
            //                break;
            out.write("</add>\n");
            out.close();
            fileCount++;
            out = new FileWriter(outDirectory.getPath() + "/data_0"
                    + ((fileCount < 10) ? "0" + fileCount : fileCount) + ".xml", false);
            out.write("<add>\n");
        }
        if (verbose) {
            if (count % 1000 == 0)
                System.out.print('.');
            if (count % 10000 == 0)
                System.out.println(" " + count);
        }
    }
    if (verbose)
        System.out.println(" " + count);
    out.write("</add>\n");
    out.close();
    in.close();
}