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:json_csv.JSON2CSV.java

public void printCuisineLookupTable(Recipes recipes) {
    Recipes newRecipes = recipes;//from ww w  .java 2  s . c  om
    List<String> printLookupTable = newRecipes.getCuisineMap();
    BufferedWriter ctw = null;

    try {

        StringBuffer oneLine = new StringBuffer();
        ctw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("cuisine.csv"), "UTF-8"));

        //iterates through the map and print
        for (String cuisine : printLookupTable) {

            ctw.write(cuisine);
            ctw.newLine();
        }

        ctw.flush();
        ctw.close();
    } catch (UnsupportedEncodingException e) {
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}

From source file:de.micromata.genome.util.collections.OrderedProperties.java

/**
 * Store0./*from ww w  .  jav a 2  s  . c om*/
 *
 * @param bw the bw
 * @param comments the comments
 * @param escUnicode the esc unicode
 * @param replacer the replacer
 * @throws RuntimeIOException the runtime io exception
 */
private void store0(BufferedWriter bw, String comments, boolean escUnicode, KeyValueReplacer replacer)
        throws RuntimeIOException {
    if (comments != null) {
        PropertiesReadWriter.writeComments(bw, comments);
    }
    try {
        bw.write("#" + new Date().toString());
        bw.newLine();
        for (Map.Entry<String, String> me : entrySet()) {
            String key = me.getKey();
            String val = me.getValue();
            if (replacer != null) {
                Pair<String, String> p = replacer.replace(Pair.make(key, val), this);
                if (p == null) {
                    continue;
                }
                key = p.getKey();
                val = p.getValue();
            }
            key = PropertiesReadWriter.saveConvert(key, true, escUnicode, true);
            /*
             * No need to escape embedded and trailing spaces for value, hence pass false to flag.
             */
            val = PropertiesReadWriter.saveConvert(val, false, escUnicode, false);
            bw.write(key + "=" + val);
            bw.newLine();
        }
        bw.flush();
    } catch (IOException ex) {
        throw new RuntimeIOException(ex);
    }
}

From source file:org.apache.hadoop.hive.metastore.tools.TestSchemaToolForMetastore.java

private File generateTestScript(String[] stmts) throws IOException {
    File testScriptFile = File.createTempFile("schematest", ".sql");
    testScriptFile.deleteOnExit();/*from   ww w .  j  ava  2  s .c  om*/
    FileWriter fstream = new FileWriter(testScriptFile.getPath());
    BufferedWriter out = new BufferedWriter(fstream);
    for (String line : stmts) {
        out.write(line);
        out.newLine();
    }
    out.close();
    return testScriptFile;
}

From source file:netdecoder.NetDecoder.java

public static void saveFlowMatrix(Map<String, Map<String, Double>> flowMatrix, String control, String disease,
        String file) throws IOException {

    File f = new File(file);
    if (!f.exists()) {
        f.createNewFile();/* w w w  .j a  v  a2  s . co m*/
    }
    FileWriter fw = new FileWriter(f.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    bw.write("edge\t" + control + "\t" + disease);
    bw.newLine();
    for (String edge : flowMatrix.keySet()) {
        bw.write(edge);
        Map<String, Double> states = flowMatrix.get(edge);
        for (String state : states.keySet()) {
            bw.write("\t" + states.get(state));
        }
        bw.newLine();
    }
    bw.close();
}

From source file:javazoom.jlgui.player.amp.playlist.BasePlaylist.java

/**
 * Saves playlist in M3U format.//from   www .j a va  2s.com
 */
public boolean save(String filename) {
    // Implemented by C.K
    if (_playlist != null) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(filename));
            bw.write("#EXTM3U");
            bw.newLine();
            Iterator it = _playlist.iterator();
            while (it.hasNext()) {
                PlaylistItem pli = (PlaylistItem) it.next();
                bw.write("#EXTINF:" + pli.getM3UExtInf());
                bw.newLine();
                bw.write(pli.getLocation());
                bw.newLine();
            }
            return true;
        } catch (IOException e) {
            log.info("Can't save playlist", e);
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException ioe) {
                log.info("Can't close playlist", ioe);
            }
        }
    }
    return false;
}

From source file:org.clothocad.phagebook.controllers.MiscControllers.java

@RequestMapping(value = "/selectColumns", method = RequestMethod.POST)
public void selectColumns(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws IOException, ServletException {
    /*//from ww  w.  ja  v a 2s.  c  o  m
     String SERIAL_NUMBER = params.get("serialNumber");
     String PRODUCT_NAME = params.get("productName");
     String PRODUCT_URL = params.get("productUrl");
     String PRODUCT_DESCRIPTION = params.get("productDescription");
     String QUANTITY = params.get("quantity");
     String COMPANY_NAME = params.get("companyName");
     String COMPANY_URL = params.get("companyUrl");
     String COMPANY_DESCRIPTION = params.get("companyDescription");
     String COMPANY_CONTACT = params.get("companyContact");
     String COMPANY_PHONE = params.get("companyPhone");
     String UNIT_PRICE = params.get("unitPrice");
     String TOTAL_PRICE = params.get("totalPrice");
     */
    System.out.println("Reached doPost");
    String id = params.get("orderId");
    System.out.println(id);
    if ((id != null) && (!id.equals(""))) {
        System.out.println("ID is not null");
        List<OrderColumns> orderColumns = new ArrayList<>();
        System.out.println("Serial Number " + params.get("serialNumber"));
        System.out.println("Product Name :: " + params.get("productName"));
        if ("true".equals(params.get("serialNumber"))) {
            orderColumns.add(OrderColumns.SERIAL_NUMBER);
        }

        if ("true".equals(params.get("productName"))) {
            orderColumns.add(OrderColumns.PRODUCT_NAME);
        }
        if ("true".equals(params.get("productUrl"))) {
            orderColumns.add(OrderColumns.PRODUCT_URL);
        }
        if ("true".equals(params.get("productDescription"))) {
            orderColumns.add(OrderColumns.PRODUCT_DESCRIPTION);
        }
        if ("true".equals(params.get("quantity"))) {
            orderColumns.add(OrderColumns.QUANTITY);
        }
        if ("true".equals(params.get("companyName"))) {
            orderColumns.add(OrderColumns.COMPANY_NAME);
        }
        if ("true".equals(params.get("companyUrl"))) {
            orderColumns.add(OrderColumns.COMPANY_URL);
        }
        if ("true".equals(params.get("companyDescription"))) {
            orderColumns.add(OrderColumns.COMPANY_DESCRIPTION);
        }
        if ("true".equals(params.get("companyContact"))) {
            orderColumns.add(OrderColumns.COMPANY_CONTACT);
        }
        if ("true".equals(params.get("companyPhone"))) {
            orderColumns.add(OrderColumns.COMPANY_PHONE);
        }
        if ("true".equals(params.get("unitPrice"))) {
            orderColumns.add(OrderColumns.UNIT_PRICE);
        }
        if ("true".equals(params.get("totalPrice"))) {
            orderColumns.add(OrderColumns.TOTAL_PRICE);
        }

        System.out.println("Order Columns " + orderColumns);

        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        String username = this.backendPhagebookUser;
        String password = this.backendPhagebookPassword;
        Map loginMap = new HashMap();
        loginMap.put("username", username);
        loginMap.put("credentials", password);

        clothoObject.login(loginMap);
        System.out.println("HERE AT SELECT 1");
        Order order = ClothoAdapter.getOrder(id, clothoObject);
        System.out.println("HERE AT SELECT 2");
        List<String> orderFormLines = createOrderForm(order, orderColumns);
        System.out.println(orderFormLines);

        String filepath = MiscControllers.class.getClassLoader().getResource(".").getPath();
        System.out.println("File path ::" + filepath);
        filepath = filepath.substring(0, filepath.indexOf("/target/"));
        System.out.println("\nTHIS IS THE FILEPATH: " + filepath);

        String filepathOrderForm = filepath + "/orderForm.csv";
        File file = new File(filepathOrderForm);

        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        for (String line : orderFormLines) {
            writer.write(line);
            writer.newLine();
        }

        writer.flush();
        writer.close();

        PrintWriter reponseWriter = response.getWriter();
        reponseWriter.println(filepathOrderForm);
        reponseWriter.flush();
        reponseWriter.close();
        clothoObject.logout();
        conn.closeConnection();
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}

From source file:com.sliit.normalize.NormalizeDataset.java

public int whiteningData() {
    System.out.println("whiteningData");

    int nums = 0;
    try {//  ww  w .ja va 2  s  . c om

        if (tempFIle != null && tempFIle.exists()) {

            csv.setSource(tempFIle);
        } else {

            csv.setSource(csvFile);
        }
        Instances instances = csv.getDataSet();
        if (instances.numAttributes() > 10) {
            instances.setClassIndex(instances.numAttributes() - 1);
            RandomProjection random = new RandomProjection();
            random.setDistribution(
                    new SelectedTag(RandomProjection.GAUSSIAN, RandomProjection.TAGS_DSTRS_TYPE));
            reducedDiemensionFile = new File(csvFile.getParent() + "/tempwhite.csv");
            if (!reducedDiemensionFile.exists()) {

                reducedDiemensionFile.createNewFile();
            }
            // CSVSaver saver = new CSVSaver();
            /// saver.setFile(reducedDiemensionFile);
            random.setInputFormat(instances);
            //saver.setRetrieval(AbstractSaver.INCREMENTAL);
            BufferedWriter writer = new BufferedWriter(new FileWriter(reducedDiemensionFile));
            for (int i = 0; i < instances.numInstances(); i++) {

                random.input(instances.instance(i));
                random.setNumberOfAttributes(10);
                random.setReplaceMissingValues(true);
                writer.write(random.output().toString());
                writer.newLine();
                //saver.writeIncremental(random.output());
            }
            writer.flush();
            writer.close();
            nums = random.getNumberOfAttributes();
        } else {

            nums = instances.numAttributes();
        }
    } catch (IOException e) {

        log.error("Error occurred:" + e.getMessage());
    } catch (Exception e) {

        log.error("Error occurred:" + e.getMessage());
    }
    return nums;
}

From source file:org.lieuofs.extraction.commune.ExtractionGeTax.java

public void extraire() throws IOException {
    CommuneCritere critere = new CommuneCritere();
    Calendar cal = Calendar.getInstance();
    cal.set(2012, Calendar.JANUARY, 1);
    critere.setDateValiditeApres(cal.getTime());
    cal.set(2012, Calendar.DECEMBER, 31);
    critere.setDateValiditeAvant(cal.getTime());
    List<ICommuneSuisse> communes = gestionnaire.rechercher(critere);
    Collections.sort(communes, new Comparator<ICommuneSuisse>() {
        @Override//  w  w w  .  j  a v  a2  s .c o m
        public int compare(ICommuneSuisse o1, ICommuneSuisse o2) {
            return o1.getNumeroOFS() - o2.getNumeroOFS();
        }
    });
    // Attention, le fichier est une iste historise des communes.
    // Une commune peut donc figurer 2 fois dans le fichier
    Set<Integer> numOFS = new HashSet<Integer>(3000);
    int nbreCommune = 0;
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(new File("ExtractionCommuneGETaX2012.csv")), Charset.forName("ISO8859-1")));

    for (ICommuneSuisse commune : communes) {
        if (!numOFS.contains(commune.getNumeroOFS())) {
            nbreCommune++;
            numOFS.add(commune.getNumeroOFS());
            writer.write(String.valueOf(commune.getNumeroOFS()));
            writer.write(";");
            writer.write(commune.getNomCourt());
            writer.write(";");
            writer.write(commune.getCanton().getCodeIso2());
            writer.newLine();
            System.out.println(commune.getNumeroOFS() + " " + commune.getNomCourt());
        }
    }
    writer.close();
    System.out.println("Nbre commune : " + nbreCommune);
}

From source file:cn.org.once.cstack.service.impl.ScriptingServiceImpl.java

public void execute(String scriptContent, String login, String password) throws ServiceException {
    logger.info(scriptContent);/*from   w  ww .j ava  2s.co m*/

    File tmpFile = null;
    FileWriter fileWriter = null;
    BufferedWriter writer = null;
    ProcessBuilder processBuilder = null;
    try {
        tmpFile = File.createTempFile(login, ".cmdFile");
        fileWriter = new FileWriter(tmpFile);
        writer = new BufferedWriter(fileWriter);
        String commandConnect = CONNECT_CMD.replace("#USER", login).replace("#PASSWORD", password)
                .replace("#HOST", host);
        logger.debug(commandConnect);
        writer.append(commandConnect);
        writer.newLine();
        writer.append(scriptContent);
        writer.newLine();
        writer.append(DISCONNECT_CMD);
        writer.flush();
        logger.debug(writer.toString());

        File fileCLI = new File(pathCLI);
        if (!fileCLI.exists()) {
            System.out.println("Error ! ");
            StringBuilder msgError = new StringBuilder(512);
            msgError.append(
                    "\nPlease run manually (1) : mkdir -p " + pathCLI.substring(0, pathCLI.lastIndexOf("/")));
            msgError.append(
                    "\nPlease run manually (2) : wget https://github.com/Treeptik/cloudunit/releases/download/1.0/CloudUnitCLI.jar -O "
                            + pathCLI);
            throw new ServiceException(msgError.toString());
        }

        processBuilder = new ProcessBuilder("java", "-jar", pathCLI, "--cmdfile", tmpFile.getAbsolutePath());
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        try {
            while ((line = reader.readLine()) != null) {
                logger.info(line);
                if (line.contains("not found"))
                    throw new ServiceException("Syntax error : " + line);
                if (line.contains("Invalid or corrupt jarfile"))
                    throw new ServiceException("Invalid or corrupt jarfile");
            }
        } finally {
            reader.close();
        }

    } catch (IOException e) {
        StringBuilder msgError = new StringBuilder(512);
        msgError.append("login=").append(login);
        msgError.append(", password=").append(password);
        msgError.append(", scriptContent=").append(scriptContent);
        logger.error(msgError.toString(), e);
    } finally {
        try {
            fileWriter.close();
        } catch (Exception ignore) {
        }
        try {
            writer.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:co.uk.randompanda30.sao.modules.util.BackupUtil.java

public void backup() {
    TEMP.isBackingup = true;/*  ww  w.j a va  2s  . c o  m*/

    SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy-HH:mm:ss-z");
    f.setTimeZone(TimeZone.getTimeZone("Europe/London"));

    ArrayList<File> fq = new ArrayList<>();

    File ff = new File(toStore);

    FileUtils.listFiles(ff, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE).stream()
            .filter(fff -> fff.getName().endsWith(".zip")).forEach(fq::add);

    if (!fq.isEmpty() && fq.size() >= 5) {
        File[] fil = fq.toArray(new File[fq.size()]);
        Arrays.sort(fil, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);

        fil[0].delete();
    }

    size = 0;
    files = 0;

    p = 0;
    lp = -1;

    time = f.format(GregorianCalendar.getInstance().getTime());

    logFile = new File(toStoreLogs + time + ".log");

    if (!new File(toStore).exists()) {
        new File(toStore).mkdir();
    }

    if (!logFile.exists()) {
        try {
            logFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Dispatch.sendMessage((String) Messages.MessagesValues.MODULES_BACKUP_STARTED.value, null);

    Bukkit.getOnlinePlayers().stream().filter(player -> player.hasPermission("backup.notification"))
            .forEach(player -> Dispatch
                    .sendMessage((String) Messages.MessagesValues.MODULES_BACKUP_STARTED.value, player));

    Thread t = new Thread(new Runnable() {
        boolean nc = false;

        @Override
        public void run() {
            String s = "zip -r " + toStore + time + ".zip " + toBackup;

            for (String exclusion : (List<String>) Config.ConfigValues.BACKUP_EXCLUSIONPATHS.value) {
                String nex = exclusion.endsWith("/") ? exclusion : exclusion + "/";
                s += " -x " + toBackup + nex + "\\" + "*";
            }

            startBackupTimer();

            File file = new File(toBackup);

            // FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)
            listFDIR(file.getAbsolutePath());

            try {
                Process process = Runtime.getRuntime().exec(s);
                InputStreamReader is = new InputStreamReader(process.getInputStream());
                BufferedReader buff = new BufferedReader(is);

                FileOutputStream fos = new FileOutputStream(logFile);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

                String line;

                while ((line = buff.readLine()) != null) {
                    files++;

                    bw.write(line);
                    bw.newLine();

                    updatePercentage();
                }
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            nc = true;

            Dispatch.sendMessage((String) Messages.MessagesValues.MODULES_BACKUP_STOPPED.value, null);

            Bukkit.getOnlinePlayers().stream().filter(player -> player.hasPermission("backup.notification"))
                    .forEach(player -> Dispatch.sendMessage(
                            (String) Messages.MessagesValues.MODULES_BACKUP_STOPPED.value, player));

            if (TEMP.pendingRestart) {
                // Message
                new ShutdownTask().runTaskTimer(SAO.getPlugin(), 0L, 20L);
            }
        }

        private void updatePercentage() {
            double d = (files / size) * 100;
            p = (int) d;
        }

        private void startBackupTimer() {
            new BukkitRunnable() {
                @Override
                public void run() {
                    if (!nc) {
                        String m = (String) Messages.MessagesValues.MODULES_BACKUP_PERCENTAGE.value;
                        m = m.replace("%perc", Integer.toString(p));
                        m = m.replace("%done", Integer.toString((int) files));
                        m = m.replace("%files", Integer.toString((int) size));

                        if (p != lp) {
                            lp = p;

                            Dispatch.sendMessage(m, null);

                            for (Player player : Bukkit.getOnlinePlayers()) {
                                if (player.hasPermission("backup.notification")) {
                                    Dispatch.sendMessage(m, player);
                                }
                            }
                        }
                    } else {
                        TEMP.isBackingup = false;
                        startTimer();
                        this.cancel();
                    }
                }
            }.runTaskTimer(SAO.getPlugin(), 0L, 100L);
        }
    });
    t.start();
}