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:mendeley2kindle.KindleDAO.java

public void commit() throws IOException {
    File path = new File(kindleLocal);
    File file = new File(path, KINDLE_COLLECTIONS_JSON);
    log.log(Level.FINER, "writing collections data: " + file);
    if (!file.exists() || file.canWrite()) {
        file.getParentFile().mkdirs();//  w  ww.  j  a  va2s .  com
        FileWriter fw = new FileWriter(file);
        fw.write(collections.toString());
        fw.close();
        log.log(Level.FINE, "Saved kindle collections: " + file);
    } else {
        log.log(Level.SEVERE, "CANNOT write Kindle collections data. Aborting..." + file);
    }
}

From source file:MSUmpire.SearchResultWriter.PepXMLWriter.java

public void Write() throws IOException, XmlPullParserException {
    int minlength = Integer.MAX_VALUE;
    int maxlength = 0;
    int maxmiss = 0;
    for (PepIonID pepIonID : PepList) {
        if (pepIonID.Sequence.length() > maxlength) {
            maxlength = pepIonID.Sequence.length();
        }//from  www  . j a va 2s .c  o m
        if (pepIonID.Sequence.length() < minlength) {
            minlength = pepIonID.Sequence.length();
        }
        if (pepIonID.getNMissedCleavages() > maxmiss) {
            maxmiss = pepIonID.getNMissedCleavages();
        }
    }

    FastaParser_V2 fastaparser = FastaParser_V2.FasterSerialzationRead(Fasta);
    if (fastaparser == null) {
        fastaparser = new FastaParser_V2(Fasta);
        fastaparser.digestion(maxmiss, minlength, maxlength, "DECOY");
    }
    Header();
    sb.append("<msms_run_summary base_name=\"" + FilenameUtils.getBaseName(Filename)
            + "\" search_engine=\"Umpire\" >\n");
    SearchSummary();
    int index = 0;
    for (PepIonID pepIonID : PepList) {
        ArrayList<ParentProtein> parentprots = new ArrayList<>();
        if (!fastaparser.PeptideList.containsKey(pepIonID.Sequence)) {
            Logger.getRootLogger().warn(pepIonID.Sequence + " is not found as tryptic peptides in " + Fasta
                    + ". Searching protein sequences..");
            for (String acc : fastaparser.ProteinList.keySet()) {
                String ProtSeq = fastaparser.ProteinList.get(acc).Seq;
                if (ProtSeq.contains(pepIonID.Sequence)) {
                    ParentProtein prot = new ParentProtein();
                    prot.Acc = acc;
                    prot.Des = fastaparser.ProteinList.get(acc).Des;
                    int aaindex = ProtSeq.indexOf(pepIonID.Sequence) - 1;
                    if (aaindex >= 0) {
                        prot.PreAA = ProtSeq.charAt(aaindex);
                    }
                    aaindex = ProtSeq.indexOf(pepIonID.Sequence) + pepIonID.Sequence.length();
                    if (aaindex < ProtSeq.length()) {
                        prot.NextAA = ProtSeq.charAt(aaindex);
                    }
                    parentprots.add(prot);
                }
            }
        } else {
            for (String acc : fastaparser.PeptideList.get(pepIonID.Sequence).Proteins) {
                String ProtSeq = fastaparser.ProteinList.get(acc).Seq;
                if (ProtSeq.contains(pepIonID.Sequence)) {
                    ParentProtein prot = new ParentProtein();
                    prot.Acc = acc;
                    prot.Des = fastaparser.ProteinList.get(acc).Des;
                    int aaindex = ProtSeq.indexOf(pepIonID.Sequence) - 1;
                    if (aaindex >= 0) {
                        prot.PreAA = ProtSeq.charAt(aaindex);
                    }
                    aaindex = ProtSeq.indexOf(pepIonID.Sequence) + pepIonID.Sequence.length();
                    if (aaindex < ProtSeq.length()) {
                        prot.NextAA = ProtSeq.charAt(aaindex);
                    }
                    parentprots.add(prot);
                }
            }
        }

        if (parentprots.isEmpty()) {
            Logger.getRootLogger().warn(pepIonID.Sequence + " is not found in " + Fasta);
        } else {
            sb.append("<spectrum_query spectrum=\"" + pepIonID.GetKey() + "\" precursor_neutral_mass=\""
                    + pepIonID.CalcNeutralPepMass() + "\" assumed_charge=\"" + pepIonID.Charge + "\" index=\""
                    + (index++) + "\" retention_time_sec=\"" + pepIonID.PeakRT * 60f + "\">\n"
                    + "<search_result>\n" + "<search_hit hit_rank=\"1\" peptide=\"" + pepIonID.Sequence
                    + "\" peptide_prev_aa=\"" + parentprots.get(0).PreAA + "\" peptide_next_aa=\""
                    + parentprots.get(0).NextAA + "\" protein=\"" + parentprots.get(0).Acc
                    + "\" protein_descr=\"" + parentprots.get(0).Des + "\" num_tot_proteins=\""
                    + parentprots.size() + "\" num_matched_ions=\"" + pepIonID.GetFragCount()
                    + "\" tot_num_ions=\"" + 2 * (pepIonID.Sequence.length() - 1)
                    + "\" calc_neutral_pep_mass=\"" + pepIonID.CalcNeutralPepMass() + "\" massdiff=\""
                    + (pepIonID.CalcNeutralPepMass() - pepIonID.ObservedMass()) + "\" num_missed_cleavages=\""
                    + pepIonID.getNMissedCleavages() + "\" is_rejected=\"0\">\n");

            for (int i = 1; i < parentprots.size(); i++) {
                sb.append("<alternative_protein protein=\"" + parentprots.get(i).Acc + "\" protein_descr=\""
                        + parentprots.get(i).Des + "\" num_tol_term=\"2\" peptide_prev_aa=\""
                        + parentprots.get(i).PreAA + "\" peptide_next_aa=\"" + parentprots.get(i).NextAA
                        + "\"/>");
            }
            //                        + "<modification_info modified_peptide=\"KITIADCGQLE\">\n"
            //                        + "<mod_aminoacid_mass position=\"7\" mass=\"160.0306\"/>\n"
            //                        + "</modification_info>\n"                        
            //                        + "<analysis_result analysis=\"peptideprophet\">\n"
            //                        + "<peptideprophet_result probability=\"0.8297\" all_ntt_prob=\"(0.0059,0.3657,0.8297)\">\n"
            //                        + "<search_score_summary>\n"
            //                        + "<parameter name=\"fval\" value=\"1.6872\"/>\n"
            //                        + "<parameter name=\"ntt\" value=\"2\"/>\n"
            //                        + "<parameter name=\"nmc\" value=\"0\"/>\n"
            //                        + "<parameter name=\"massd\" value=\"4.011\"/>\n"
            //                        + "<parameter name=\"isomassd\" value=\"0\"/>\n"
            //                        + "</search_score_summary>\n"
            //                        + "</peptideprophet_result>\n"
            //                        + "</analysis_result>\n"
            sb.append("<analysis_result analysis=\"interprophet\">\n" + "<interprophet_result probability=\""
                    + pepIonID.TargetedProbability() + "\">\n"
                    //                        + "<search_score_summary>\n"
                    //                        + "<parameter name=\"nrs\" value=\"0\"/>\n"
                    //                        + "<parameter name=\"nsi\" value=\"0\"/>\n"
                    //                        + "<parameter name=\"nsm\" value=\"0\"/>\n"
                    //                        + "</search_score_summary>\n"
                    + "</interprophet_result>\n" + "</analysis_result>\n" + "</search_hit>\n"
                    + "</search_result>\n" + "</spectrum_query>\n");
        }

    }
    sb.append("</msms_run_summary>\n");
    sb.append("</msms_pipeline_analysis>\n");
    FileWriter writer = new FileWriter(Filename);
    writer.write(sb.toString());
    writer.close();
}

From source file:c3.ops.priam.backup.MetaData.java

@SuppressWarnings("unchecked")
public void set(List<AbstractBackupPath> bps, String snapshotName) throws Exception {
    File metafile = createTmpMetaFile();
    FileWriter fr = new FileWriter(metafile);
    try {/*w w  w  .  java2 s . c o  m*/
        JSONArray jsonObj = new JSONArray();
        for (AbstractBackupPath filePath : bps)
            jsonObj.add(filePath.getRemotePath());
        fr.write(jsonObj.toJSONString());
    } finally {
        IOUtils.closeQuietly(fr);
    }
    AbstractBackupPath backupfile = pathFactory.get();
    backupfile.parseLocal(metafile, BackupFileType.META);
    backupfile.time = backupfile.parseDate(snapshotName);
    try {
        upload(backupfile);

        addToRemotePath(backupfile.getRemotePath());
        if (metaRemotePaths.size() > 0) {
            notifyObservers();
        }
    } finally {
        FileUtils.deleteQuietly(metafile);
    }
}

From source file:de.uzk.hki.da.cb.CreateDCAction.java

private void writeDCBackToPIP(String audience, String updatedDcContent) throws IOException {

    wa.pipMetadataFile(audience, METADATA_STREAM_ID_DC).delete();
    FileWriter fw = null;
    try {//from w  w w . j  a v  a 2 s .co  m
        fw = new FileWriter(wa.pipMetadataFile(audience, METADATA_STREAM_ID_DC));
        fw.write(updatedDcContent);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (fw != null)
            fw.close();
    }
}

From source file:fr.paris.lutece.plugins.rss.service.RssGeneratorService.java

/**
 * Creates the pushrss file in the directory
 *
 * @param strRssFileName The file's name that must be deleted
 * @param strRssDocument The content of the new RSS file
 *///from   w w  w . j  a v a  2 s .c o m
public static void createFileRss(String strRssFileName, String strRssDocument) {
    FileWriter fileRssWriter;

    try {
        // fetches the pushRss directory path
        String strFolderPath = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH, "");

        // Test if the pushRss directory exist and create it if it doesn't exist
        if (!new File(strFolderPath).exists()) {
            File fileFolder = new File(strFolderPath);
            fileFolder.mkdir();
        }

        // Creates a temporary RSS file
        String strFileRss = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH, "")
                + strRssFileName;
        String strFileDirectory = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH,
                "");
        File fileRss = new File(strFileRss);
        File fileRssDirectory = new File(strFileDirectory);
        File fileRssTemp = File.createTempFile("tmp", null, fileRssDirectory);
        fileRssWriter = new FileWriter(fileRssTemp);
        fileRssWriter.write(strRssDocument);
        fileRssWriter.flush();
        fileRssWriter.close();

        // Deletes the file if the file exists and renames the temporary file into the file
        if (new File(strFileRss).exists()) {
            File file = new File(strFileRss);
            file.delete();
        }

        fileRssTemp.renameTo(fileRss);
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (NullPointerException e) {
        AppLogService.error(e.getMessage(), e);
    }
}

From source file:com.tealeaf.ResourceDownloaderTask.java

private void stringToFile(File file, String content) {

    FileWriter fileWriter = null;
    try {//  ww  w . j a  va  2  s  .  co  m
        fileWriter = new FileWriter(file);
        fileWriter.write(content);
        fileWriter.close();
    } catch (IOException e) {
        logger.log(e);
    } finally {
        try {
            fileWriter.close();
        } catch (IOException e) {
            logger.log(e);
        }
    }
}

From source file:com.jgui.ttscrape.htmlunit.FetchController.java

private void writeContent(int i, HtmlPage currentPage) {
    try {//from  w ww  . ja va  2  s.c  o  m
        FileWriter writer = new FileWriter("results/raw" + i + ".xml");
        writer.write(currentPage.asXml());
        writer.close();
    } catch (Exception ex) {
        logger.error("Failed to write raw content", ex);
    }
}

From source file:com.dmsl.anyplace.tasks.DownloadRadioMapTaskXY.java

@Override
protected String doInBackground(Void... params) {

    try {/*  w ww  . jav  a 2  s  .c  o  m*/
        if (json_req == null)
            return "Error creating the request!";
        // check sdcard state
        File root;
        try {
            root = AnyplaceUtils.getRadioMapFoler(ctx, mBuildID, mFloor_number);
        } catch (Exception e) {
            return e.getMessage();
        }

        // rename the radiomap according to the floor
        String filename_radiomap_download = AnyplaceUtils.getRadioMapFileName(mFloor_number);
        String mean_fname = filename_radiomap_download;
        String rbf_weights_fname = mean_fname.replace(".txt", "-rbf-weights.txt");
        String parameters_fname = mean_fname.replace(".txt", "-parameters.txt");

        File okfile = new File(root, "ok.txt");
        if (!mForceDonwload && okfile.exists()) {
            success = true;
            return "Successfully read radio map from cache!";
        }

        okfile.delete();

        // changed in order to receive only the radio map for the
        // current floor
        String response = NetworkUtils.downloadHttpClientJsonPost(AnyplaceAPI.getRadioDownloadXY(), json_req);
        JSONObject json = new JSONObject(response);

        if (json.getString("status").equalsIgnoreCase("error")) {
            return "Error Message: " + json.getString("message");
        }

        String means = json.getString("map_url_mean");
        String parameters = json.getString("map_url_parameters");
        String weights = json.getString("map_url_weights");

        // create the credentials JSON in order to send and download the
        // radio map
        JSONObject json_credentials = new JSONObject();
        json_credentials.put("username", "username");
        json_credentials.put("password", "pass");
        String cred_str = json_credentials.toString();

        String ms = NetworkUtils.downloadHttpClientJsonPost(means, cred_str);
        String ps = NetworkUtils.downloadHttpClientJsonPost(parameters, cred_str);
        String ws = NetworkUtils.downloadHttpClientJsonPost(weights, cred_str);

        // check if the files downloaded correctly
        if (ms.contains("error") || ps.contains("error") || ws.contains("error")) {
            json = new JSONObject(response);
            return "Error Message: " + json.getString("message");
        }

        FileWriter out;

        out = new FileWriter(new File(root, rbf_weights_fname));
        out.write(ws);
        out.close();

        out = new FileWriter(new File(root, parameters_fname));
        out.write(ps);
        out.close();

        out = new FileWriter(new File(root, mean_fname));
        out.write(ms);
        out.close();

        out = new FileWriter(okfile);
        out.write("ok;version:0;");
        out.close();

        success = true;
        return "Successfully saved radio maps!";

    } catch (ConnectTimeoutException e) {
        return "Connecting to Anyplace service is taking too long!";
    } catch (SocketTimeoutException e) {
        return "Communication with the server is taking too long!";
    } catch (Exception e) {
        return "Error downloading radio maps [ " + e.getMessage() + " ]";
    }

}

From source file:fast.servicescreen.server.RequestServiceImpl.java

/**
 * This method try to form a given String
 * into a file, and save it as .js//from w w  w.j a va 2 s  .c o m
 * */
@SuppressWarnings("deprecation")
@Override
public String saveJsFileOnServer(boolean isLocal, String opName, String preHTMLCode, String transCode,
        String postHTMLCode) {
    //the HTML file content
    String htmlContent = preHTMLCode + transCode + postHTMLCode;
    String answer = "";

    try {
        //getting class path
        path = ".";
        String classLocation = getClassLocation();
        String installDir;
        int prefixLength;

        //if local save into war, if not save into webapps folder
        if (isLocal) {
            prefixLength = classLocation.indexOf("ServiceScreenDesignerWep");
            prefixLength += "ServiceScreenDesignerWep".length();
            path = classLocation.substring(0, prefixLength) + "/wrapper/";
        } else {
            prefixLength = classLocation.indexOf("ServiceDesignerWep");
            prefixLength += "ServiceDesignerWep".length();
            installDir = classLocation.substring(0, prefixLength);
            path = URLDecoder.decode(installDir) + "/wrapper/";

            if (new File(path).mkdir()) {
                answer += "Create folder 'wrapper'       ";
            }
        }

        //configure filename (for html)
        String baseFileName = path + opName + "Op";
        String fileName = baseFileName + ".html";

        //write file
        FileWriter writer = new FileWriter(fileName, false);
        writer.write(htmlContent);
        writer.close();

        //configure filename (for javascript)
        fileName = baseFileName + ".js";
        writer = new FileWriter(fileName, false);

        //write file
        writer.write(transCode);
        writer.close();

        answer += "The file now exists in: " + path;
    } catch (Exception e) {
        answer += " Error: " + e.getLocalizedMessage();

        return answer;
    }

    return answer;
}

From source file:com.nts.alphamaleWeb.controller.ServiceController.java

@RequestMapping("/exportJobs")
@ResponseBody//ww  w. j  a  va  2 s  .  co m
public String exportJobs(@RequestParam(required = true) String jobJsons) {
    ResultBody<Boolean> result = new ResultBody<Boolean>();
    try {
        String fileName = "export_" + System.currentTimeMillis() + ".txt";
        File file = new File(fileName);
        FileWriter fw = new FileWriter(file, false);
        fw.write(jobJsons);
        fw.flush();
        fw.close();
        result.setCode(Code.OK, true);
    } catch (Exception e) {
        e.printStackTrace();
        result.setCode(Code.F100);
    }
    return result.toJson();
}