Example usage for java.io FileWriter append

List of usage examples for java.io FileWriter append

Introduction

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

Prototype

@Override
    public Writer append(CharSequence csq) throws IOException 

Source Link

Usage

From source file:sk.mlp.file.WriteNewTrack.java

/**
 * Metda processRequest je obslun metda, ktor sa vol po vyvolan danho servletu na strane pouvatea. 
 * Pri?om sa servlet vykonva na strane servera.
 * @param request - objekt poiadavky, ktor sa prena zo strany klienta na stranu servera
 * @param response - objekt odozvy servera, ktor sa prena zo strany servera na stranu klienta
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 *//*from w  ww . ja v a 2  s .  co  m*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    String trackName = session.getAttribute("trackName").toString();
    String trackDescr = session.getAttribute("trackDescr").toString();
    String trackActivity = session.getAttribute("trackActivity").toString();
    String access = session.getAttribute("access").toString();

    session.setAttribute("trackNameExist", "False");
    //        if (system.startsWith("Windows")) {
    //        
    //            FileReader namereader = new FileReader("C:\\path.pth");
    //            BufferedReader in = new BufferedReader(namereader);
    //                    
    //            String pathToUpl = in.readLine();
    //            
    //            String tempPath = pathToUpl + session.getAttribute("username") + "\\Temp" + "\\";
    //            //String tempPath = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\";
    //            File tempFile = new File(tempPath);
    //            if (tempFile.exists()) {
    //                System.out.println("Mam temp a vymazujem!");
    //                FileUtils.deleteDirectory(tempFile);
    //                //tempFile.delete();
    //                FileLogger.getInstance().createNewLog("Warning: Found old temp folder which belongs to " + session.getAttribute("username") + " !!! Successfuly delete the old temp.");
    //            }
    //        } else {
    //            String tempPath = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/" + session.getAttribute("username") + "/Temp" + "/";
    //            File tempFile = new File(tempPath);
    //            if (tempFile.exists()) {
    //                System.out.println("Mam temp a vymazujem!");
    //                FileUtils.deleteDirectory(tempFile);
    //                FileLogger.getInstance().createNewLog("Warning: Found old temp folder which belongs to " + session.getAttribute("username") + " !!! Successfuly delete the old temp.");
    //            }
    //        }

    if (system.startsWith("Windows")) {

        pathToFile = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "\\Temp" + "\\";
        pathToMultimedia = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "\\Temp"
                + "\\Multimedia\\";
        //pathToFile = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\";
        //pathToMultimedia = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\Multimedia\\";
    } else {
        pathToFile = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "/Temp" + "/";
        pathToMultimedia = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "/Temp"
                + "/Multimedia/";
    }

    File tempF = new File(pathToFile + "Temp.txt");
    if (tempF.exists()) {
        FileUtils.forceDelete(tempF);
        FileLogger.getInstance()
                .createNewLog("Warning: Found tamp file Temp.txt in WriteNewTrack which belongs to user "
                        + session.getAttribute("username") + " while writing new track " + trackName + " !!!");
    }

    File multF = new File(pathToMultimedia);
    MultimediaSearcher searcher = new MultimediaSearcher();
    searcher.setSearchFolder(pathToMultimedia);
    String[] files = searcher.startSearchWithoutTrack();
    if (files.length >= 1) {
        session.setAttribute("isMultimedia", "True");
    }

    new File(pathToFile).mkdirs();
    File file = new File(pathToFile, "Temp.txt"); // Write to destination file. Pouyivaj filename!
    boolean create = file.createNewFile();
    //System.out.println("Vytvoril: " + create);

    if (file.exists()) {
        String latLngStr = request.getParameter("textBox");

        FileWriter writer = new FileWriter(file, true);
        BufferedWriter buf = new BufferedWriter(writer);

        writer.append(latLngStr);

        buf.close();
        writer.close();
    }
    if (session.getAttribute("isMultimedia") != null) {
        request.getRequestDispatcher("SynchronizeDrawTrack.jsp").forward(request, response);
    } else {
        try {

            String pathToTemp;
            String pathToTempFile;
            String pathToMultimediaFiles;

            String filename = trackName + ".gpx";
            if (system.startsWith("Windows")) {

                pathToFile = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "\\" + trackName
                        + "\\";
                pathToTemp = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "\\" + "Temp"
                        + "\\";
                pathToTempFile = pathToFile + "Temp.txt";
                //pathToFile = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\" + trackName + "\\";
                //pathToTemp = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\" + "Temp" + "\\";
                //pathToTempFile = pathToFile + "Temp.txt";
                pathToMultimediaFiles = pathToFile + "Multimedia" + "\\";
                //                    File fTemp = new File(pathToMultimediaFiles);
                //                    if(!fTemp.exists()){
                //                        fTemp.mkdirs();
                //                    }
            } else {
                pathToFile = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "/" + trackName
                        + "/";
                pathToTemp = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "/" + "Temp"
                        + "/";
                pathToTempFile = pathToFile + "Temp.txt";
                pathToMultimediaFiles = pathToFile + "Multimedia" + "/";
                //                    File fTemp = new File(pathToMultimediaFiles);
                //                    if(!fTemp.exists()){
                //                        fTemp.mkdirs();
                //                    }
            }

            File oldFile = new File(pathToTemp);
            File newFile = new File(pathToFile);
            oldFile.renameTo(newFile);

            GPXParser parser = new GPXParser(pathToFile, filename, session.getAttribute("username").toString(),
                    trackName);
            parser.readFromTrackPoints(pathToTempFile, trackName, trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly created GPXParser in STEP 3 for track " + trackName + " .");
            parser.searchForMultimediaFilesWithoutCorrection(pathToMultimediaFiles);

            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly founded multimedia files in STEP 3 for track " + trackName + " .");
            parser.parseFromTrackPoints(trackActivity, trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly parsed GPX file in STEP 3 for track " + trackName + " .");
            parser.createGPXFile(trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly generated GPX file in STEP 3 for track " + trackName + " .");

            DatabaseServices databaseServices = new DatabaseServices();

            databaseServices.createNewTrack(trackName, trackDescr, trackActivity, pathToFile,
                    (int) databaseServices.findUserByEmail(session.getAttribute("username").toString())
                            .getIdent(),
                    (Date) parser.getStartAndEndDate().get(0), (Date) parser.getStartAndEndDate().get(1),
                    access, parser.getStartAddress(), parser.getEndAddress(), parser.getTrackLengthKm(),
                    parser.getTrackMinElevation(), parser.getTrackMaxElevation(), parser.getTrackHeightDiff(),
                    parser.getTrackDuration(), "Drawed");

            TLVLoader loader = new TLVLoader();
            loader.readTLVFile(pathToFile, trackName);
            PDFTrackGenerator generator = new PDFTrackGenerator(loader, pathToFile, trackName);
            generator.generateTrackPDFA4(2, null, 640, 640, 1, parser.getStartAndEndDate().get(0).toString(),
                    parser.getStartAndEndDate().get(1).toString(), trackActivity,
                    session.getAttribute("username").toString());

            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly created new track in STEP 3 for track " + trackName + " .");

            if (loader.getTrackPoints().get(0).getInternetElevation() == 0 && loader.getTrackPoints()
                    .get(loader.getTrackPoints().size() - 1).getInternetElevation() == 0) {
                session.setAttribute("Limit", "True");
            }

        } catch (Exception ex) {
            System.out.println("Error: Unable to create .tlv file!");
            FileLogger.getInstance().createNewLog("ERROR: Unable to create user's "
                    + request.getSession().getAttribute("username") + " track " + trackName + " in STEP 3 !!!");
            //vloyit oznacenie chyby parsera!!!
            ex.printStackTrace();
        }
        request.getRequestDispatcher("ShowTracks.jsp").forward(request, response);
    }

}

From source file:coral.service.ExpServable.java

@Override
public void broadcast(Integer id, String msg) {
    BlockingQueue<Message> outQueue = clients.get(id);

    FileWriter fw = screenwriter.get(id);
    if (fw != null) {
        try {/*from   w ww.ja  v a  2  s.  co m*/
            fw.append(msg);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    outQueue.add(new Message("vset", viewname, "text/html", "YES", msg.getBytes()));
}

From source file:dk.netarkivet.archive.checksum.DatabaseChecksumArchive.java

/**
 * Method for appending a 'wrong' entry in the wrongEntryFile. It will be noted which time the wrong entry was
 * appended: date + " : " + wrongRecord.
 *
 * @param wrongRecord The record to append.
 * @throws IOFailure If the wrong record cannot be appended correctly.
 *//*  w  w w. jav a  2 s .c om*/
private synchronized void appendWrongRecordToWrongEntryFile(String wrongRecord) throws IOFailure {
    try {
        // Create the string to append: date + 'wrong record'.
        String entry = new Date().toString() + " : " + wrongRecord + "\n";

        // get a filewriter for the checksum file, and append the record.
        boolean appendToFile = true;
        FileWriter fwrite = new FileWriter(wrongEntryFile, appendToFile);
        fwrite.append(entry);

        // close fileWriter.
        fwrite.flush();
        fwrite.close();
    } catch (IOException e) {
        log.warn("Cannot put a bad record to the 'wrongEntryFile'.", e);
        throw new IOFailure("Cannot put a bad record to the 'wrongEntryFile'.", e);
    }
}

From source file:de.tap.easy_xkcd.fragments.comics.FavoritesFragment.java

private void exportFavorites() {
    //Export the full favorites list as text
    StringBuilder sb = new StringBuilder();
    String newline = System.getProperty("line.separator");
    for (int i = 0; i < favorites.length; i++) {
        sb.append(favorites[i]).append(" - ");
        sb.append(prefHelper.getTitle(favorites[i]));
        sb.append(newline);//from   w w  w.j  ava2s  . c  o  m
    }
    try {
        File sdCard = prefHelper.getOfflinePath();
        File dir = new File(sdCard.getAbsolutePath() + "/easy xkcd");
        File file = new File(dir, "favorites.txt");
        FileWriter writer = new FileWriter(file);
        writer.append(sb.toString());
        writer.flush();
        writer.close();
        //Provide option to send to any app that accepts text/plain content
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        Uri uri = FileProvider.getUriForFile(getActivity(), "de.tap.easy_xkcd.fileProvider", file);
        sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.pref_export)));
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), "Export failed", Toast.LENGTH_SHORT).show();
    }
}

From source file:org.ala.spatial.analysis.index.LayerDistanceIndex.java

public void run() {
    FileWriter fw = null;
    try {//from  w w w.ja  va 2 s . co m
        fw = new FileWriter(filename, true);
        try {
            while (true) {
                String s = toDisk.take();
                fw.append(s + "\n");
                fw.flush();
            }
        } catch (Exception e) {
            //This is expected to occur after all distances are
            //calculated and the calling of interrupt.  
            //Might as well attempt to finish up.
            try {
                while (toDisk.size() > 0) {
                    String s = toDisk.take();
                    fw.append(s + "\n");
                    fw.flush();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (fw != null) {
            try {
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:tml.conceptmap.ConceptMap.java

public void writeToXML(String filename) throws Exception {
    FileWriter writer = new FileWriter(filename);
    writer.append("<?xml version=\"1.0\"?>\n");
    writer.append("<conceptmap>\n");
    for (Concept concept : this.vertexSet()) {
        writer.append("  <concept label=\"");
        writer.append(StringEscapeUtils.escapeXml(concept.getTerm()));
        writer.append("\"/>\n");
    }//from   w w w  . j  a  v  a 2s .c  om
    for (Relationship<Concept> relationship : this.edgeSet()) {
        writer.append("  <relationship label=\"");
        writer.append(StringEscapeUtils.escapeXml(relationship.getLinkingWord()));
        writer.append("\">\n");
        writer.append("    <concept label=\"");
        writer.append(StringEscapeUtils.escapeXml(relationship.getSource().getTerm()));
        writer.append("\"/>\n");
        writer.append("    <concept label=\"");
        writer.append(StringEscapeUtils.escapeXml(relationship.getTarget().getTerm()));
        writer.append("\"/>\n");
        writer.append("  </relationship>\n");
    }
    writer.append("</conceptmap>\n");
    writer.close();
}

From source file:com.compomics.pladipus.controller.setup.InstallActiveMQ.java

/**
 * Writes an executable script to the desktop
 * @throws IOException// w  w w . j  a v a 2s . c  o  m
 */
public void writeWorkerBash() throws IOException {
    String os = System.getProperty("os.name");
    String jarLocation = findFile(activeMQFolder, "activemq.jar").getAbsolutePath();
    String command = "java -jar " + jarLocation + " start";
    FileWriter bashWriter;
    if (os.toLowerCase().contains("windows")) {
        File bashFile = new File(System.getProperty("user.home") + "/Desktop/Pladipus-ActiveMQ.bat");
        bashWriter = new FileWriter(bashFile);
    } else {
        File bashFile = new File(System.getProperty("user.home") + "/Desktop/Pladipus-ActiveMQ.sh");
        bashWriter = new FileWriter(bashFile);
    }
    bashWriter.append(command).flush();
    bashWriter.close();
}

From source file:fr.gael.dhus.service.SystemService.java

/**
 * Restores the desired dump of the database and Solr index. To  restore the
 * system must be stopped.This method produces the properties file to
 * generates new restored database and Solr index.
 * @param date of the dump to restore.//from  w  ww.j  a  v a2 s.c o  m
 * @throws DHusDumpException if date does not corresponds to an
 * existing dump.
 */
public void restoreDumpDatabase(Date date) {
    File retorationDir = new File(cfgManager.getDatabaseConfiguration().getDumpPath(),
            String.format("dump-%020d", date.getTime()));
    if (!(retorationDir.exists() && retorationDir.isDirectory())) {
        throw new DHusDumpException("Dump of \"" + date + "\" not found");
    }

    try {
        String path = retorationDir.getAbsolutePath();
        SolrConfiguration solrConfig = cfgManager.getSolrConfiguration();
        FileWriter writer = new FileWriter(RESTORATION_PROPERTIES);

        // Database
        writer.append("dhus.db.backup=").append(path).append("/").append(BACKUP_DATABASE_NAME)
                .append(".tar.gz");
        writer.append('\n');
        writer.append("dhus.db.location=").append(getDBDirectory());
        writer.append('\n');

        // Solr index
        writer.append("dhus.solr.backup.name=").append(BACKUP_INDEX_NAME);
        writer.append('\n');
        writer.append("dhus.solr.backup.location=").append(path);
        writer.append('\n');
        writer.append("dhus.solr.core.name=").append(solrConfig.getCore());
        writer.append('\n');
        writer.append("dhus.solr.home=").append(solrConfig.getPath());
        writer.append('\n');

        writer.flush();
        writer.close();
    } catch (IOException e) {
        logger.warn("Can not perform restoration.", e);
        return;
    }

    DHuS.stop(8);
}

From source file:umberto.WeightedClusterCoefficient.WeightedClusterCoefficient.java

/**
 * Generate distribution file.//w w  w.  java2s  . c om
 *
 * @param sFileName file path.
 */
public void generateSaveFile(String sFileName, Map<Float, Float> map) {
    try {
        FileWriter writer = new FileWriter(sFileName);
        Set<Map.Entry<Float, Float>> set = map.entrySet();
        int k = 0;
        for (Map.Entry<Float, Float> element : set) {
            writer.append(element.getKey().toString());
            writer.append(' ');
            writer.append(element.getValue().toString());
            k = k + 1;
            if (k != map.size()) {
                writer.append('\n');
            }
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:au.org.ala.spatial.analysis.layers.LayerDistanceIndex.java

public void run() {
    FileWriter fw = null;
    try {/*from w  ww.  j a  va2  s.  c o m*/
        fw = new FileWriter(filename, true);
        try {
            while (true) {
                String s = toDisk.take();
                fw.append(s + "\n");
                fw.flush();
            }
        } catch (Exception e) {
            //This is expected to occur after all distances are
            //calculated and the calling of interrupt.  
            //Might as well attempt to finish up.
            try {
                while (toDisk.size() > 0) {
                    String s = toDisk.take();
                    fw.append(s + "\n");
                    fw.flush();
                }
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }

        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (fw != null) {
            try {
                fw.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}