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:icevaluation.ICEvaluation.java

public void startICEval() {
    loadkeyInfo();// ww  w  . j a v  a2  s . c  o  m
    System.out.println("Total Key: " + totalkey);
    //String queryOriginal = "sports game";
    //String queryCover = "jack raihanee";
    BufferedReader reader = null;
    try {
        File file = new File("data/topic/QueryLogs.txt");
        reader = new BufferedReader(new FileReader(file));
        String line;
        line = reader.readLine();
        if (line == null) {
            System.out.println("Please uptate query file correctly");
            return;
        }
        int numCoverQ = Integer.parseInt(line);
        String originQuery = "";
        String coverQuery = "";
        while ((line = reader.readLine()) != null) {//original query
            //System.out.println("Original: "+line);
            originQuery = line;
            for (int i = 0; i < numCoverQ; i++) {
                line = reader.readLine();
                if (line == null) {
                    System.out.println("Please uptate query file correctly");
                    return;
                }
                coverQuery = line;
                double IC = getIC(originQuery, coverQuery);

                FileWriter fw;
                fw = new FileWriter("data/topic/IC_topic.txt", true);
                fw.write(IC + "\n");
                fw.close();

                System.out.println(IC);

            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writeKeyInfoBack();
        System.out.println("Key status write succesfully");
    }
}

From source file:com.verigreen.collector.jobs.HistoryCleanerJob.java

private void updateHistory(Map<String, List<JSONObject>> newHistory) {
    FileWriter file;
    VerigreenNeededLogic.history = newHistory;
    try {/*from  ww  w.  j a v  a 2  s . c o m*/
        file = new FileWriter(System.getenv("VG_HOME") + "//history.json");
        JSONObject history = new JSONObject(VerigreenNeededLogic.history);
        file.write(history.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        VerigreenLogger.get().error(getClass().getName(), RuntimeUtils.getCurrentMethodName(),
                String.format("Failed updating json file: " + System.getenv("VG_HOME") + "\\history.json", e));
    }
}

From source file:com.ut.healthelink.service.hl7toTxt.java

public String TranslateHl7toTxt(String fileLocation, String fileName, int orgId) throws Exception {

    Organization orgDetails = organizationmanager.getOrganizationById(orgId);
    fileSystem dir = new fileSystem();

    dir.setDir(orgDetails.getcleanURL(), "templates");

    String templatefileName = orgDetails.getparsingTemplate();

    URLClassLoader loader = new URLClassLoader(
            new URL[] { new URL("file://" + dir.getDir() + templatefileName) });

    // Remove the .class extension
    Class cls = loader.loadClass(templatefileName.substring(0, templatefileName.lastIndexOf('.')));

    Constructor constructor = cls.getConstructor();

    Object HL7Obj = constructor.newInstance();

    Method myMethod = cls.getMethod("HL7toTxt", new Class[] { File.class });

    /* Get the uploaded HL7 File */
    fileLocation = fileLocation.replace("/Applications/bowlink/", "").replace("/home/bowlink/", "")
            .replace("/bowlink/", "");
    dir.setDirByName(fileLocation);/*from  w  w  w .j  a v  a 2  s . co m*/

    File hl7File = new File(dir.getDir() + fileName + ".hr");

    /* Create the output file */
    String newfileName = new StringBuilder()
            .append(hl7File.getName().substring(0, hl7File.getName().lastIndexOf("."))).append(".")
            .append("txt").toString();

    File newFile = new File(dir.getDir() + newfileName);

    if (newFile.exists()) {
        try {

            if (newFile.exists()) {
                int i = 1;
                while (newFile.exists()) {
                    int iDot = newfileName.lastIndexOf(".");
                    newFile = new File(dir.getDir() + newfileName.substring(0, iDot) + "_(" + ++i + ")"
                            + newfileName.substring(iDot));
                }
                newfileName = newFile.getName();
                newFile.createNewFile();
            } else {
                newFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        newFile.createNewFile();
        newfileName = newFile.getName();

    }

    FileWriter fw = new FileWriter(newFile, true);

    /* END */
    String fileRecords = (String) myMethod.invoke(HL7Obj, new Object[] { hl7File });

    fw.write(fileRecords);

    fw.close();

    return newfileName;

}

From source file:de.uzk.hki.da.grid.CTIrodsCommandLineConnector.java

private File testiRule() throws IOException {
    File testFile = new File(tmpDir + "test.r");
    FileWriter writer = new FileWriter(testFile, false);
    writer.write("checkiRule { \n " + "*len=0;\n" + "msiStrlen(\"hallo\",*len);\n" + "}\n" + "INPUT null\n"
            + "OUTPUT *len");
    writer.close();//from  ww  w.  j ava  2  s .  co  m

    return testFile;
}

From source file:de.csw.expertfinder.mediawiki.api.MediaWikiAPI.java

public static void eraseRedirects(MediaWikiAPI w) {
    try {//from w  ww .ja v  a 2s  . c  o  m
        BufferedReader in = new BufferedReader(
                new FileReader("Z:\\csw\\Dipomarbeit\\Evaluierung\\Alle Artikel.txt"));
        FileWriter out = new FileWriter("Z:\\csw\\Dipomarbeit\\Evaluierung\\Alle Artikel ohne Redirects.txt");

        String articleName;
        while ((articleName = in.readLine()) != null) {
            String actualName = w.getActualArticleName(articleName);
            if (articleName.equals(actualName)) {
                out.write(articleName + "\n");
            }
            //            else {
            //               System.out.println("Omitting: " + articleName + " -> " + actualName);
            //            }
        }
        out.flush();
        out.close();
        in.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MediaWikiAPIException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.saiku.web.rest.resources.BasicRepositoryResource.java

/**
 * /*from   w  w w  . ja  v a2  s.c  o m*/
 * @param queryName - The name of the query.
 * @param newName - The saved query name.
 * @return An OK Status, if the save was good, otherwise a NOT FOUND Status when not saved properly.
 */
@POST
@Produces({ "application/json" })
@Path("/{queryname}")
public Status saveQuery(@PathParam("queryname") String queryName, @FormParam("newname") String newName) {
    try {
        String xml = olapQueryService.getQueryXml(queryName);
        if (newName != null) {
            queryName = newName;
        }

        if (repo != null && xml != null) {
            if (!queryName.endsWith(".saiku")) {
                queryName += ".saiku";
            }
            String uri = repo.getName().getPath();
            if (!uri.endsWith("" + File.separatorChar)) {
                uri += File.separatorChar;
            }

            File queryFile = new File(uri + URLDecoder.decode(queryName, "UTF-8"));
            if (queryFile.exists()) {
                queryFile.delete();
            } else {
                queryFile.createNewFile();
            }
            FileWriter fw = new FileWriter(queryFile);
            fw.write(xml);
            fw.close();
            return (Status.OK);
        } else {
            throw new Exception("Cannot save query because repo or xml is null repo(" + (repo == null)
                    + ") xml(" + (xml == null) + " )");
        }
    } catch (Exception e) {
        log.error("Cannot save query (" + queryName + ")", e);
        return (Status.NOT_FOUND);
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.ManifestParserImplFastTest.java

@Test
public void testAddFileToManifest() throws IOException, NoSuchAlgorithmException, ParseException {
    // write a new manifest file (to make sure we know what is in it)
    final File manifest = new File(
            SAMPLE_DIR + "qclive/manifestParser/center_disease.platform.Level_1.1.0.0/TEMP_MANIFEST.txt");
    FileWriter writer = null;

    try {//from   w  ww  .ja  va2  s.  com
        //noinspection IOResourceOpenedButNotSafelyClosed
        writer = new FileWriter(manifest);
        writer.write("12345  hello\n");
    } finally {
        IOUtils.closeQuietly(writer);
    }

    // this file should be added to the manifest
    final File toAdd = new File(
            SAMPLE_DIR + "qclive/manifestParser/center_disease.platform.Level_1.1.0.0/README.txt");
    try {
        parser.addFileToManifest(toAdd, manifest);
        final Map<String, String> manifestContent = parser.parseManifest(manifest);
        // only care that file has been added, not what the MD5 is
        assertTrue(manifestContent.containsKey("README.txt"));
    } finally {
        manifest.deleteOnExit();
    }
}

From source file:net.blogracy.controller.FileSharing.java

public void addFeedEntry(String id, String text, File attachment) {
    try {//  w ww .  j  a v a  2 s .c om
        String hash = hash(text);
        File textFile = new File(CACHE_FOLDER + File.separator + hash + ".txt");

        FileWriter w = new FileWriter(textFile);
        w.write(text);
        w.close();

        String textUri = seed(textFile);
        String attachmentUri = null;
        if (attachment != null) {
            attachmentUri = seed(attachment);
        }

        final List<ActivityEntry> feed = getFeed(id);
        final ActivityEntry entry = new ActivityEntryImpl();
        entry.setVerb("post");
        entry.setUrl(textUri);
        entry.setPublished(ISO_DATE_FORMAT.format(new Date()));
        entry.setContent(text);
        if (attachment != null) {
            ActivityObject enclosure = new ActivityObjectImpl();
            enclosure.setUrl(attachmentUri);
            entry.setObject(enclosure);
        }
        feed.add(0, entry);
        final File feedFile = new File(CACHE_FOLDER + File.separator + id + ".json");

        JSONArray items = new JSONArray();
        for (int i = 0; i < feed.size(); ++i) {
            JSONObject item = new JSONObject(feed.get(i));
            items.put(item);
        }
        JSONObject db = new JSONObject();
        db.put("items", items);

        FileWriter writer = new FileWriter(feedFile);
        db.write(writer);
        writer.close();

        String feedUri = seed(feedFile);
        DistributedHashTable.getSingleton().store(id, feedUri, entry.getPublished());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.tzutalin.configio.JsonConfig.java

private boolean save() {
    // If  the file exists, load it first
    if (new File(mTargetPath).exists()) {
        loadFromFile();//w  ww  . j  ava  2s  . c o  m
    }

    // Delete keys if the user removes keys but didn't call loadFromFile first
    if (mMap != null && mMap.size() != 0 && mDeleteKeySet.size() != 0) {
        for (String key : mDeleteKeySet) {
            mMap.remove(key);
        }
    }

    // Save to target path
    if (mMap != null && mMap.size() != 0) {
        JSONObject obj = new JSONObject(mMap);
        String jsonStr = obj.toString();
        Log.d(TAG, "save : " + mTargetPath + " json:" + jsonStr);
        try {
            FileWriter file = new FileWriter(mTargetPath);
            file.write(jsonStr);
            file.flush();
            file.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}