Example usage for java.io BufferedWriter newLine

List of usage examples for java.io BufferedWriter newLine

Introduction

In this page you can find the example usage for java.io BufferedWriter newLine.

Prototype

public void newLine() throws IOException 

Source Link

Document

Writes a line separator.

Usage

From source file:InterfaceModule.JRobert.java

private void exportToFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportToFileActionPerformed
    JFileChooser chooser = new JFileChooser(System.getProperty("user.dir") + "/saves/");
    chooser.setDialogTitle("Salve o relatrio");
    File fileToSave;/*from w w w. j av a  2s . c o  m*/
    int selection = chooser.showSaveDialog(this);
    if (selection == JFileChooser.APPROVE_OPTION)
        fileToSave = chooser.getSelectedFile();
    else
        return;

    try {
        FileWriter fr = new FileWriter(fileToSave);
        BufferedWriter bw = new BufferedWriter(fr);
        String[] text = jTextArea1.getText().split("\n");

        for (String s : text) {
            bw.write(s);
            bw.newLine();
        }
        bw.close();
        fr.close();
    } catch (IOException e) {

    }
}

From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java

public void writeToFile(String message) {
    // TODO Use something in org.apache.commons.io.FileUtils which does this..
    if (message.indexOf(END_TEST) > 0) {
        BufferedWriter bufferedWriter = null;
        try {//from w  w w . j  ava  2  s  .co m
            bufferedWriter = new BufferedWriter(new FileWriter(getLogFile().getPath(), true));
            bufferedWriter.newLine();
            bufferedWriter.append(message);
        } catch (IOException e) {
            // e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                // ex.printStackTrace();
            }
        }
    }
}

From source file:controllers.CensusController.java

@RequestMapping(value = "/export", method = RequestMethod.GET)
public ModelAndView export(@RequestParam int censusId) throws IOException {
    ModelAndView result;//w  ww . j  a  v  a  2s.c o m
    Census census = censusService.findOne(censusId);
    String typeOS = System.getProperty("os.name");
    String userHomeDir = System.getProperty("user.home");
    File file = null;

    // Hacemos un cambio en el directorio donde se guardar el fichero .txt
    // dependiendo de si estamos trabajando sobre Windows o sobre Linux

    if (typeOS.contains("Windows")) {
        file = new File(userHomeDir + "/Desktop/filename" + censusId + ".txt");
    } else if (typeOS.contains("Linux")) {
        file = new File(userHomeDir + "/Escritorio/filename" + censusId + ".txt");
    } else if (typeOS.contains("Mac")) {
        file = new File(userHomeDir + "/Desktop/filename" + censusId + ".txt");
    }

    // Comprobamos que el txt que vamos a crear no existe ya en este
    // directorio,
    // sino existe, creamos un txt nuevo, en caso de que exista uno, lo
    // sustituimos

    if (!file.exists()) {
        file.createNewFile();
    }

    // Aqu estamos dando el formato que queremos que tenga nuestro .txt

    FileWriter fileWriter = new FileWriter(file);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.newLine();
    bufferedWriter.write("Details of the census");
    bufferedWriter.newLine();
    bufferedWriter.newLine();
    bufferedWriter.write("Owner: " + census.getUsername());
    bufferedWriter.newLine();
    bufferedWriter.write("Name of vote: " + census.getTituloVotacion());
    bufferedWriter.newLine();
    bufferedWriter.write("Vote number: " + census.getIdVotacion());
    bufferedWriter.newLine();
    bufferedWriter.write("Start date: " + census.getFechaInicioVotacion());
    bufferedWriter.newLine();
    bufferedWriter.write("Finish date: " + census.getFechaFinVotacion());
    bufferedWriter.newLine();
    bufferedWriter.write("---------------------");
    bufferedWriter.newLine();
    bufferedWriter.newLine();
    bufferedWriter.write("Voters: ");
    bufferedWriter.newLine();

    // Todos los usuarios del sistema

    Map<String, String> mapUsers = RESTClient.getMapUSernameAndEmailByJsonAutentication();
    Collection<String> usernames = mapUsers.keySet();

    // Todos los que han votado en un censo

    Collection<String> userList = census.getVotoPorUsuario().keySet();
    if (usernames.size() != 0) {

        // Aqu compruebo que de todos los usuarios disponibles en el
        // sistema, cul de
        // ellos ha votado ya en el censo

        for (String aux : usernames) {
            for (String voter : userList) {

                // Uno de los usuarios del sistema ya ha votado en dicho
                // censo

                if (aux.equals(voter)) {

                    // Obtenemos el mapa del censo, para saber si el usuario
                    // ha votado o no

                    HashMap<String, Boolean> map = census.getVotoPorUsuario();

                    // Aadimos este usuario que ya ha votado al text

                    User user = RESTClient.getCertainUserByJsonAuthentication(voter);
                    bufferedWriter.newLine();
                    bufferedWriter.write("User_Id: " + user.getUId());
                    bufferedWriter.newLine();
                    bufferedWriter.write("Username: " + user.getUsername());
                    bufferedWriter.newLine();
                    bufferedWriter.write("Email: " + user.getEmail());
                    bufferedWriter.newLine();
                    bufferedWriter.write("Genre: " + user.getGenre());
                    bufferedWriter.newLine();
                    bufferedWriter.write("Autonomous community: " + user.getAutonomousCommunity());
                    bufferedWriter.newLine();
                    bufferedWriter.write("Age: " + user.getAge());
                    bufferedWriter.newLine();
                    bufferedWriter.write("Has voted?: " + map.get(voter));
                    bufferedWriter.newLine();
                    bufferedWriter.write("*****************");
                    bufferedWriter.newLine();
                    break;
                }
            }
        }
    } else {
        bufferedWriter.write("Nothing to display because there isn't any voters");
    }

    bufferedWriter.close();
    result = new ModelAndView("redirect:getAllCensusByCreador.do");
    return result;
}

From source file:gtu._work.ui.LoadJspFetchJavascriptUI.java

private void executeBtnActionPerformed(ActionEvent evt) {
    try {//from  w  w w.j av a2  s  .c o m
        String subName = Validate.notBlank(subNameText.getText());
        if (StringUtils.isNotBlank(tagPatternText.getText())) {
            String startP = "\\<" + tagPatternText.getText();
            String endP = "\\<\\/" + tagPatternText.getText() + "\\>";
            javascriptStart = Pattern.compile(startP, Pattern.CASE_INSENSITIVE);
            javascriptEnd = Pattern.compile(endP, Pattern.CASE_INSENSITIVE);
            JCommonUtil._jOptionPane_showMessageDialog_info(
                    String.format("tagPattern:\nstart:\n%send:\n%s", startP, endP));
        }

        long startTime = System.currentTimeMillis();

        File file = JCommonUtil.filePathCheck(filePathText.getText(), "?", false);
        List<File> fileList = new ArrayList<File>();
        if (file.isFile()) {
            fileList.add(file);
        } else {
            if (subName.startsWith(".")) {
                subName = subName.substring(1);
            }
            FileUtil.searchFilefind(file, ".*\\." + subName + "$", fileList);
        }
        File outputFile = new File(FileUtil.DESKTOP_PATH,
                "javascript_" + DateUtil.getCurrentDateTime(false) + ".txt");
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile), "utf8"));
        for (File f : fileList) {
            String content = writeScript(f);
            if (content.length() > 0) {
                writer.write(
                        "#start#" + f.getAbsolutePath() + "#==============================================");
                writer.newLine();
                writer.write(content);
                writer.write(
                        "#end  #" + f.getAbsolutePath() + "#==============================================");
                writer.newLine();
            }
        }
        writer.flush();
        writer.close();

        long duringTime = System.currentTimeMillis() - startTime;

        JCommonUtil._jOptionPane_showMessageDialog_info(
                "?,:" + fileList.size() + "\n:" + duringTime);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:com.commander4j.util.JUtility.java

public synchronized static void writeToTextFile(String filename, String text) {
    BufferedWriter bw = null;

    try {// w  w w  .j a  va  2 s.  c  o  m
        bw = new BufferedWriter(new FileWriter(filename, true));
        bw.write(text);
        bw.newLine();
        bw.flush();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally { // always close the file

        if (bw != null) {
            try {
                bw.close();
            } catch (IOException ioe2) {
            }
        }
    }
}

From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java

void addTestClassNameToJS(String className) {
    BufferedWriter bw = null;
    try {/*from   w  w w .  j a v  a2  s. co  m*/
        bw = new BufferedWriter(new FileWriter(jsFile, true));
        bw.write("testClassArray.push(\"" + className + "\");");
        bw.newLine();
        bw.flush();
    } catch (IOException ioe) {
        // DO Nothing
    } finally { // always close the file
        if (bw != null)
            try {
                bw.close();
            } catch (IOException ioe2) {
                // just ignore it
            }
    } // end try/catch/finally
}

From source file:com.amazonaws.mobileconnectors.kinesis.kinesisrecorder.FileRecordStore.java

public boolean put(final String record) throws IOException {
    boolean success = false;
    BufferedWriter writer = null;
    accessLock.lock();//from www  . j a  v  a 2 s .  c om
    try {
        writer = tryInitializeWriter();
        if (recordFile.length() + record.getBytes(StringUtils.UTF8).length <= maxStorageSize) {
            writer.write(record);
            writer.newLine();
            writer.flush();
            success = true;
        }
    } finally {
        if (writer != null) {
            writer.close();
        }
        accessLock.unlock();
    }

    return success;
}

From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java

void addFailedTestClassNameToJS(String className) {
    BufferedWriter bw = null;
    try {//from  ww  w.  jav  a  2 s  .  c  om
        bw = new BufferedWriter(new FileWriter(jsFile, true));
        bw.write("failedTestClassArray.push(\"" + className + "\");");
        bw.newLine();
        bw.flush();
    } catch (IOException ioe) {
        // DO Nothing
    } finally { // always close the file
        if (bw != null)
            try {
                bw.close();
            } catch (IOException ioe2) {
                // just ignore it
            }
    } // end try/catch/finally
}

From source file:no.imr.stox.functions.acoustic.PgNapesIO.java

public static void export(String cruise, String country, String callSignal, String path, String fileName,
        List<DistanceBO> distances, String species, Double intDist, Double pchThick) {
    // Atle: implement!
    Integer acoCat = PgNapesEchoConvert.getAcoCatFromPgNapesSpecies(species);
    BufferedWriter bWriter1 = null;
    BufferedWriter bWriter2 = null;
    try {/*from  w  ww .ja va  2s  .c  o m*/
        String fil1 = path + "/" + fileName + "_Acoustic.txt";
        String fil2 = path + "/" + fileName + "_AcousticValues.txt";

        bWriter1 = new BufferedWriter(new FileWriter(fil1));
        bWriter2 = new BufferedWriter(new FileWriter(fil2));

        bWriter1.write("Country" + "" + "\t" + "Vessel" + "" + "\t" + "Cruise" + "" + "\t" + "Log" + "" + "\t");
        bWriter1.write("Year" + "" + "\t" + "Month" + "" + "\t" + "Day" + "" + "\t" + "Hour" + "" + "\t");
        bWriter1.write("Min" + "" + "\t" + "AcLat" + "" + "\t" + "AcLon" + "" + "\t" + "Logint" + "" + "\t");
        bWriter1.write("Frequency" + "" + "\t" + "Sv_threshold");
        bWriter1.newLine();

        bWriter2.write("Country" + "" + "\t" + "Vessel" + "" + "\t" + "Cruise" + "" + "\t" + "Log" + "" + "\t");
        bWriter2.write("Year" + "" + "\t" + "Month" + "" + "\t" + "Day" + "" + "\t" + "Species" + "" + "\t");
        bWriter2.write("ChUppDepth" + "" + "\t" + "ChLowDepth" + "" + "\t" + "SA");
        bWriter2.newLine();

        Boolean isEnd = true;

        //Vertical Resolution/new channel thickness from filter
        Double totintdist = 0.0;
        Integer countdist = 0;
        Double sa50ch[] = new Double[1001]; //sa pr intdist
        Double saout[] = new Double[1001]; //sa accumulated over 5 nm. Output to files

        for (int g = 0; g < sa50ch.length; g++) {
            sa50ch[g] = 0.0;
            saout[g] = 0.0;
        }

        String hout1[] = new String[14]; // Sheet1: header info from first intdist in 5 nm dist
        for (int h = 0; h < hout1.length; h++) {
            hout1[h] = null;
        }

        String hout2[] = new String[8]; // Sheet2: header info from first intdist in 5 nm dist
        for (int h = 0; h < hout2.length; h++) {
            hout2[h] = null;
        }

        Resolution rr = new Resolution();

        //GO THROUGH ALL OBSERVATIONS IN SELECTED DATASETT ONE OBS AT THE TIME
        Integer nobs = distances.size();

        for (int line = 0; line < nobs; line++) {
            DistanceBO dist = distances.get(line);
            for (FrequencyBO f : dist.getFrequencies()) {
                FrequencyBO frequency = f;
                //PS! What if threshold change within a 5 nm ?? Use first value OK???
                String threshold = Double.toString(frequency.getThreshold());
                //String helpNumPel = Integer.toString(freq.getNum_pel_ch());

                Date d = dist.getStart_time();
                String helpymd = IMRdate.formatDate(d, "yyyyMMdd");
                String year = helpymd.substring(0, 4);
                String month = helpymd.substring(4, 6);
                String day = helpymd.substring(6, 8);

                String helphms = IMRdate.formatDate(d, "HHmmss");
                String hour = helphms.substring(0, 2);
                String min = helphms.substring(2, 4);

                // String Log = df.format(dist.getLog_start()/*LogFloor*/);
                String log = Conversion.formatDoubletoDecimalString(dist.getLog_start().doubleValue(), "0.0");

                //Check if this is the end of the integrator distance (using the filter value
                rr.setIntDist(Math.max(intDist, dist.getIntegrator_dist()));
                rr.setLog(Conversion.safeStringtoDouble(log));
                isEnd = rr.getIsEnd();

                String acLat = Conversion.formatDoubletoDecimalString(dist.getLat_start(), "0.000");
                String acLon = Conversion.formatDoubletoDecimalString(dist.getLon_start(), "0.000");
                Double helppct = dist.getPel_ch_thickness();
                Integer helppctR = (int) Math.round(helppct);

                //Number of ch per 50 meter ch
                Double vertRes = null;
                if (pchThick != null && pchThick > dist.getPel_ch_thickness()) {
                    vertRes = pchThick;
                } else {
                    vertRes = dist.getPel_ch_thickness();
                }
                Double ww = vertRes / helppct;
                Integer helpnchch = ww.intValue();
                //Number of 50 meter channels
                Integer q = frequency.getNum_pel_ch();
                Integer ww1 = frequency.getNum_pel_ch() % helpnchch;
                Integer ww2 = (frequency.getNum_pel_ch() / helpnchch);
                Integer helpnch = ww2.intValue();
                if (ww1 > 0) {
                    helpnch = helpnch + 1;
                }
                if (helpnch > sa50ch[0]) {
                    sa50ch[0] = helpnch.doubleValue();
                }

                // SUM UP P SA VALUES FOR THIS OBSERVATION IN 50 meter CHANNELS
                List<SABO> salist = frequency.getSa();

                for (Integer ch = 1; ch <= frequency.getNum_pel_ch(); ch++) {
                    if (ch <= frequency.getNum_pel_ch()) {
                        //Double saval = 0.0;
                        for (Integer i = 0; i < salist.size(); i++) {
                            //storage.getSaByFrequencyChannelTypeAcousticCategory(freq, "P", f.getId_acoustic_category());
                            SABO elm = salist.get(i);
                            if (elm.getAcoustic_category() == null || elm.getCh() == null
                                    || elm.getCh_type() == null || !elm.getCh().equals(ch)
                                    || !elm.getCh_type().equals("P")
                                    || !elm.getAcoustic_category().equalsIgnoreCase(acoCat.toString())) {
                                continue;
                            }
                            Double ch50a = (ch * helppctR.doubleValue()) % vertRes;
                            Double ch50b = (ch * helppctR.doubleValue()) / vertRes;
                            Integer ch50c = ch50b.intValue();

                            if (ch50a > 0) {
                                ch50c = ch50c + 1;
                            }
                            sa50ch[ch50c] = elm.getSa() + sa50ch[ch50c];
                            sa50ch[1000] = elm.getSa() + sa50ch[1000];
                            break;
                        }
                    }
                }

                //IF START OF A NEW 5 NM DISTANCE KEEP HEADING VALUES
                if (isEnd.equals(true)) {
                    hout1[0] = country;
                    hout1[1] = callSignal;
                    hout1[2] = cruise;
                    hout1[3] = log;
                    hout1[4] = year;
                    hout1[5] = month;
                    hout1[6] = day;
                    hout1[7] = hour;
                    hout1[8] = min;
                    hout1[9] = acLat;
                    hout1[10] = acLon;
                    //hout1[11] = Logint;
                    hout1[12] = frequency.getFreq().toString();
                    hout1[13] = threshold;

                    hout2[0] = country;
                    hout2[1] = callSignal;
                    hout2[2] = cruise;
                    hout2[3] = log;
                    hout2[4] = year;
                    hout2[5] = month;
                    hout2[6] = day;
                    hout2[7] = species;
                }

                //KEEP SA-VALUES FROM THIS INTEGRATOR DISTANCE
                if (sa50ch[0] > saout[0]) {
                    saout[0] = sa50ch[0];
                }
                for (int k = 1; k < saout.length; k++) {
                    saout[k] = saout[k] + sa50ch[k];
                }

                //Count number of intdist + totaldist
                countdist = countdist + 1;
                totintdist = totintdist + dist.getIntegrator_dist();

                boolean okIntDist = false;

                //Check if distance from previous output distance is not to  large due to holes in data:
                boolean okPrevDist = false;
                if ((rr.getEndLog() != null) && (rr.getIntDist() != null)) {
                    if ((rr.getLog() - rr.getEndLog()) - 0.05 <= rr.getIntDist()) {
                        okPrevDist = true;
                    } else {
                        okPrevDist = false;
                    }
                } else {
                    okPrevDist = true;
                }

                //Check if sum of distances is correct + check if stoplog minus startlog is equal to sum of distances
                if (rr.getIntDist() == null) {
                    okIntDist = true;
                } else {
                    if ((((rr.getIntDist() - 0.05) < totintdist) && (totintdist < (rr.getIntDist() + 0.05)))
                            && okPrevDist) {
                        okIntDist = true;
                    }
                }

                //PRINT TO FILES
                if (okIntDist && isEnd) {
                    for (int k = 1; k < saout.length; k++) {
                        saout[k] = saout[k] / countdist;
                    }

                    //Sheet file 1:
                    hout1[11] = Conversion.formatDoubletoDecimalString(totintdist, "0.0");

                    for (Integer elm = 0; elm < 14; elm++) {
                        if (hout1[elm] != null) {
                            bWriter1.write(hout1[elm] + "" + "\t");
                        } else {
                            bWriter1.write(" " + "" + "\t");
                        }
                    }
                    bWriter1.newLine();

                    //Sheet file 2:
                    for (Integer elm = 0; elm < saout[0].intValue(); elm++) {
                        for (Integer e = 0; e < 8; e++) {
                            bWriter2.write(hout2[e] + "" + "\t");
                        }
                        bWriter2.write((elm * vertRes) + "" + "\t");
                        bWriter2.write(((elm * vertRes) + vertRes) + "" + "\t");
                        String sa = String.format(Locale.UK, "%11.5f", (saout[elm + 1]));
                        bWriter2.write(sa + "" + "\t");
                        bWriter2.newLine();
                    }
                } else {
                    for (int k = 1; k < sa50ch.length; k++) {
                        sa50ch[k] = 0.0;
                    }
                }
                if (isEnd.equals(true)) {
                    for (int g = 0; g < sa50ch.length; g++) {
                        sa50ch[g] = 0.0;
                        saout[g] = 0.0;
                    }
                    //Total sa all channels, this variable is not used, test only
                    sa50ch[1000] = 0.0;
                    //Max number of 50 meter channels in 5 nm distance
                    sa50ch[0] = 0.0;

                    countdist = 0;
                    totintdist = 0.0;
                }
            } // Have to look up by frequency here in future.

        }
        bWriter1.close();
        bWriter2.close();
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }

}

From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java

private void addPakageNameToJS(String packageName) throws IOException {
    BufferedWriter bw = null;
    try {/*from ww  w  . j  a  v  a 2s  .  co  m*/
        bw = new BufferedWriter(new FileWriter(jsFile, true));
        bw.write("packageArray.push(\"" + packageName.toUpperCase() + "\");");
        bw.newLine();
        bw.flush();
    } catch (IOException ioe) {
        // DO Nothing
    } finally { // always close the file
        if (bw != null)
            try {
                bw.close();
            } catch (IOException ioe2) {
                // just ignore it
            }
    } // end try/catch/finally
}