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:ar.com.tadp.xml.rinzo.core.utils.FileUtils.java

/**
 * Guarda un documento localmente en la cache
 *//*from www.  j  a va 2 s.co  m*/
public static void saveFile(String inputFileName, File outputFile) {
    InputStream openStream = null;
    BufferedReader reader = null;
    BufferedWriter writer = null;
    try {
        File inputFile = new File(inputFileName);
        if (!inputFile.exists()) {
            openStream = new URL(inputFileName).openStream();
            InputStreamReader is = new InputStreamReader(openStream);
            String encoding = is.getEncoding();
            reader = new BufferedReader(is);
            writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(outputFile, false), encoding));

            String line = reader.readLine();
            while (line != null) {
                writer.write(line);
                writer.newLine();
                writer.flush();
                line = reader.readLine();
            }
        }
    } catch (Exception exception) {
        throw new RuntimeException("Error trying to save \'" + inputFileName + "\' in the cache.", exception);
    } finally {
        try {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (openStream != null) {
                openStream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(
                    "Error trying to close files while saving \'" + inputFileName + "\' in the cache.", e);
        }
    }
}

From source file:com.yunshan.cloudstack.vmware.util.VmwareHelper.java

public static byte[] composeDiskInfo(List<Ternary<String, String, String>> diskInfo, int disksInChain,
        boolean includeBase) throws IOException {

    BufferedWriter out = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {/*ww w  .j a v  a  2s  .c o  m*/
        out = new BufferedWriter(new OutputStreamWriter(bos));

        out.write("disksInChain=" + disksInChain);
        out.newLine();

        out.write("disksInBackup=" + diskInfo.size());
        out.newLine();

        out.write("baseDiskIncluded=" + includeBase);
        out.newLine();

        int seq = disksInChain - 1;
        for (Ternary<String, String, String> item : diskInfo) {
            out.write(String.format("disk%d.fileName=%s", seq, item.first()));
            out.newLine();

            out.write(String.format("disk%d.baseFileName=%s", seq, item.second()));
            out.newLine();

            if (item.third() != null) {
                out.write(String.format("disk%d.parentFileName=%s", seq, item.third()));
                out.newLine();
            }
            seq--;
        }

        out.newLine();
    } finally {
        if (out != null)
            out.close();
    }

    return bos.toByteArray();
}

From source file:core.Utility.java

public static void generateCategoryDataCSV(String word) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(new File("output files/" + word + ".csv")));

    int count = 0;
    ArrayList<String> miscList = new ArrayList();

    // calculate miscelleneous list
    for (Entity e : Global.entities) {
        if (e.categories.isEmpty()) {
            miscList.add(e.word);// ww w.  ja  v  a  2  s .  c  o  m
        }
    }

    count = miscList.size();

    // calculate maximum count
    for (Category c : Global.categories) {
        int itemCount = c._relatedWords.size();
        count = itemCount > count ? itemCount : count;
        writer.write(c._name + ",,");
    }
    writer.write("Miscellineous");

    writer.newLine();

    for (int c = 0; c < count; c++) {
        for (Category cat : Global.categories) {
            String oldWord = (c <= (cat._OriginalList.size() - 1)) ? cat._OriginalList.get(c)._name : "";
            String newWord = (c <= (cat._NewList.size() - 1)) ? cat._NewList.get(c)._name : "";

            // write
            writer.write(oldWord + "," + newWord + ",");
        }

        String miscWord = (c <= (miscList.size() - 1)) ? miscList.get(c) : "";

        // write  misc word
        writer.write(miscWord + ",");
        writer.newLine();
    }
    //        for (int i = -1; i < Global.categories.size(); i++) {
    //            if (i > -1) {
    //                writer.newLine();
    //
    //                Category c = Global.categories.get(i);
    //
    //                for (Entity e : Global.entities) {
    //                    writer.write((e.categories.contains(c._name) ? "Yes" : "No") + ",");
    //                }
    //
    //                writer.write(c._name);
    //            } else {
    //                for (Entity e : Global.entities) {
    //                    writer.write(e.word + ",");
    //                }
    //
    //                writer.write("CATEGORY");
    //            }
    //        }
    //
    //        writer.newLine();
    //        for (Entity e : Global.entities) {
    //            writer.write((e.categories.isEmpty() ? "Yes" : "No") + ",");
    //        }
    //        writer.write("Miscellaneous");

    writer.close();
}

From source file:ml.shifu.shifu.fs.ShifuFileUtils.java

public static void writeLines(@SuppressWarnings("rawtypes") Collection collection, String filePath,
        SourceType sourceType) throws IOException {
    BufferedWriter writer = getWriter(filePath, sourceType);
    try {//from  w ww . j a  va 2 s .c  o m
        for (Object object : collection) {
            if (object != null) {
                writer.write(object.toString());
                writer.newLine();
            }
        }
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:ml.shifu.shifu.fs.ShifuFileUtils.java

public static void copyToLocal(SourceFile sourceFile, String partFilePrefix, String localOutputPath)
        throws IOException {
    HdfsPartFile hdfsPartFile = new HdfsPartFile(sourceFile.getPath(), sourceFile.getSourceType(),
            partFilePrefix);/*w ww . j av a  2s. co  m*/
    BufferedWriter writer = new BufferedWriter(new FileWriter(localOutputPath));
    String line = null;
    try {
        while ((line = hdfsPartFile.readLine()) != null) {
            writer.write(line);
            writer.newLine();
        }
    } catch (Exception e) {
        // ignore
    } finally {
        IOUtils.closeQuietly(writer);
        hdfsPartFile.close();
    }
}

From source file:com.t_oster.visicut.misc.Helper.java

public static void installInkscapeExtension() throws FileNotFoundException, IOException {
    File src = new File(getVisiCutFolder(), "inkscape_extension");
    if (!src.exists() || !src.isDirectory()) {
        throw new FileNotFoundException("Not a directory: " + src);
    }/*from www .j  a  v a 2  s.  c  om*/

    String profile_path = System.getenv("INKSCAPE_PORTABLE_PROFILE_DIR");

    if (profile_path == null) {
        profile_path = System.getenv("INKSCAPE_PROFILE_DIR");
    }

    File trg;

    if (profile_path != null) {
        trg = new File(profile_path);
    } else {
        if (isWindows()) {
            trg = new File(System.getenv("AppData"));
        } else {
            trg = new File(FileUtils.getUserDirectory(), ".config");
        }
    }

    trg = new File(new File(trg, "inkscape"), "extensions");

    if (!trg.exists() && !trg.mkdirs()) {
        throw new FileNotFoundException("Can't create directory: " + trg);
    }
    for (File f : src.listFiles()) {
        if ("visicut_export.py".equals(f.getName())) {
            File target = new File(trg, "visicut_export.py");
            BufferedReader r = new BufferedReader(new FileReader(f));
            BufferedWriter w = new BufferedWriter(new FileWriter(target));
            String line = r.readLine();
            while (line != null) {
                if ("VISICUTDIR=\"\"".equals(line)) {
                    line = "VISICUTDIR=r\"" + getVisiCutFolder().getAbsolutePath() + "\"";
                }
                w.write(line);
                w.newLine();
                line = r.readLine();
            }
            w.flush();
            w.close();
            r.close();
        } else if (f.getName().toLowerCase().endsWith("inx") || f.getName().toLowerCase().endsWith("py")) {
            FileUtils.copyFileToDirectory(f, trg);
        }
    }
}

From source file:dsfixgui.FileIO.DSFixFileController.java

/**
 *Writes a string to a text file/*from w  w w .j a  va2s.  co m*/
 * 
 * @param filePath
 *  the path of the file to be read, including the filename
 * @param text
 *  the String to be written to the file; can be more than one line.
 * @param overwrite
 *  determines whether the user wants to overwrite the write file if it
 *  already exists. If true, pre-existing file will be overwritten
 * @throws IIOException
 *  if the write file already exists and the user allowed overwriting, but
 *  the file could not be overwritten
 * @throws AccessDeniedException
 *  if the write file already exists but the user didn't allow overwriting
 * @throws IOException
 *  if an error occurs initializing the BufferedWriter
 */
public static void writeTextFile(String filePath, String text, boolean overwrite)
        throws IIOException, IOException, AccessDeniedException {

    //The file to be written
    File writeFile = new File(filePath);
    if (writeFile.exists() && overwrite) {
        //If file exists, try to delete it
        if (!writeFile.delete()) {
            //If file cannot be deleted, throw OIOException
            throw new IIOException("Could not delete pre-existing file: " + filePath);
        }
    } else if (writeFile.exists() && !overwrite) {
        //If file exists but is not allowed to be overwritten, throw AccessDeniedException
        throw new AccessDeniedException(writeFile.getPath());
    }

    //Format each linebreak to be displayed correctly in a text file
    String formattedText = text.replaceAll("\n", String.format("%n"));
    //Initialize BufferedWriter to write string to file
    BufferedWriter fileWriter = new BufferedWriter(new FileWriter(writeFile));
    //Write the file
    Scanner scanner = new Scanner(formattedText);
    while (scanner.hasNextLine()) {
        fileWriter.write(scanner.nextLine());
        fileWriter.newLine();
    }

    fileWriter.close();
}

From source file:com.cloud.hypervisor.vmware.util.VmwareHelper.java

public static byte[] composeDiskInfo(List<Ternary<String, String, String>> diskInfo, int disksInChain,
        boolean includeBase) throws IOException {

    BufferedWriter out = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {//from ww  w  .ja  v a2 s . c o m
        out = new BufferedWriter(new OutputStreamWriter(bos, "UTF-8"));

        out.write("disksInChain=" + disksInChain);
        out.newLine();

        out.write("disksInBackup=" + diskInfo.size());
        out.newLine();

        out.write("baseDiskIncluded=" + includeBase);
        out.newLine();

        int seq = disksInChain - 1;
        for (Ternary<String, String, String> item : diskInfo) {
            out.write(String.format("disk%d.fileName=%s", seq, item.first()));
            out.newLine();

            out.write(String.format("disk%d.baseFileName=%s", seq, item.second()));
            out.newLine();

            if (item.third() != null) {
                out.write(String.format("disk%d.parentFileName=%s", seq, item.third()));
                out.newLine();
            }
            seq--;
        }

        out.newLine();
    } finally {
        if (out != null)
            out.close();
    }

    return bos.toByteArray();
}

From source file:canreg.client.analysis.Tools.java

/**
 *
 * @param popoutput//from  www.  j  a  v a2s .co m
 * @param startYear
 * @param populations
 * @param separator
 * @throws IOException
 * @throws canreg.common.database.IncompatiblePopulationDataSetException
 */
public static void writePopulationsToFile(BufferedWriter popoutput, int startYear,
        PopulationDataset[] populations, String separator)
        throws IOException, IncompatiblePopulationDataSetException {
    String popheader = "YEAR" + separator;
    popheader += "AGE_GROUP_LABEL" + separator;
    popheader += "AGE_GROUP" + separator;
    popheader += "SEX" + separator;
    popheader += "COUNT" + separator;
    popheader += "REFERENCE_COUNT" + separator;
    popheader += "AGE_GROUP_SIZE";
    popoutput.append(popheader);
    popoutput.newLine();
    int thisYear = startYear;
    for (PopulationDataset popset : populations) {
        if (popset != null) {
            String[] ageGroupNames = popset.getAgeGroupStructure().getAgeGroupNames();
            for (PopulationDatasetsEntry pop : popset.getAgeGroups()) {
                popoutput.append(thisYear + "").append(separator);
                popoutput.append(ageGroupNames[pop.getAgeGroup()]).append(separator);
                popoutput.append(pop.getStringRepresentationOfAgeGroupsForFile(separator)).append(separator);
                // get reference pop
                popoutput.append(
                        popset.getReferencePopulationForAgeGroupIndex(pop.getSex(), pop.getAgeGroup()) + "")
                        .append(separator);
                popoutput
                        .append(popset.getAgeGroupStructure().getSizeOfAgeGroupByIndex(pop.getAgeGroup()) + "");
                popoutput.newLine();
            }
        }
        thisYear++;
    }
    popoutput.flush();
}

From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java

/**
 * @param vehicleDistances/*from  w  w w. j a  v a  2 s.  c om*/
 * @param iterationFilename
 */
public static void writeVehicleDistances(Map<Id<Vehicle>, double[]> vehicleDistances,
        String iterationFilename) {
    String header = "vehicleId;drivenDistance_m;occupiedDistance_m;emptyDistance_m;revenueDistance_pm";
    BufferedWriter bw = IOUtils.getBufferedWriter(iterationFilename);
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);
    try {
        bw.write(header);
        for (Entry<Id<Vehicle>, double[]> e : vehicleDistances.entrySet()) {
            double drivenDistance = e.getValue()[0];
            double revenueDistance = e.getValue()[1];
            double occDistance = e.getValue()[2];
            double emptyDistance = drivenDistance - occDistance;
            bw.newLine();
            bw.write(e.getKey().toString() + ";" + format.format(drivenDistance) + ";"
                    + format.format(occDistance) + ";" + format.format(emptyDistance) + ";"
                    + format.format(revenueDistance));
        }
        bw.flush();
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}