Example usage for java.io BufferedWriter write

List of usage examples for java.io BufferedWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:it.tizianofagni.sparkboost.DataUtils.java

/**
 * Write a text file on Hadoop file system by using standard Hadoop API.
 *
 * @param outputPath The file to be written.
 * @param content    The content to put in the file.
 *//*from  w w w .  j  a va2 s .co  m*/
public static void saveHadoopTextFile(String outputPath, String content) {
    try {
        Configuration configuration = new Configuration();
        Path file = new Path(outputPath);
        Path parentFile = file.getParent();
        FileSystem hdfs = FileSystem.get(file.toUri(), configuration);
        if (parentFile != null)
            hdfs.mkdirs(parentFile);
        OutputStream os = hdfs.create(file, true);
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        br.write(content);
        br.close();
        hdfs.close();
    } catch (Exception e) {
        throw new RuntimeException("Writing Hadoop text file", e);
    }
}

From source file:playground.dgrether.analysis.charts.utils.DgChartWriter.java

public static void writeChartDataToFile(String filename, JFreeChart chart) {
    filename += ".txt";
    try {//from  w w w. j  a v  a 2  s  . c o  m
        BufferedWriter writer = IOUtils.getBufferedWriter(filename);
        try { /*read "try" as if (plot instanceof XYPlot)*/
            XYPlot xy = chart.getXYPlot();
            String yAxisLabel = xy.getRangeAxis().getLabel();

            String xAxisLabel = "";
            if (xy.getDomainAxis() != null) {
                xAxisLabel = xy.getDomainAxis().getLabel();
            }
            String header = "#" + xAxisLabel + "\t " + yAxisLabel;
            writer.write(header);
            writer.newLine();
            //write the header
            writer.write("#");
            for (int i = 0; i < xy.getDatasetCount(); i++) {
                XYDataset xyds = xy.getDataset(i);
                int seriesIndex = 0;
                int maxItems = 0;
                int seriesCount = xyds.getSeriesCount();
                while (seriesIndex < seriesCount) {
                    writer.write("Series " + xyds.getSeriesKey(seriesIndex).toString());
                    if (seriesIndex < seriesCount - 1) {
                        writer.write("\t \t");
                    }
                    if (xyds.getItemCount(seriesIndex) > maxItems) {
                        maxItems = xyds.getItemCount(seriesIndex);
                    }
                    seriesIndex++;
                }
                writer.newLine();

                //write the data
                Number xValue, yValue = null;
                for (int itemsIndex = 0; itemsIndex < maxItems; itemsIndex++) {
                    for (int seriesIdx = 0; seriesIdx < seriesCount; seriesIdx++) {
                        if (seriesIdx < xyds.getSeriesCount() && itemsIndex < xyds.getItemCount(seriesIdx)) {
                            xValue = xyds.getX(seriesIdx, itemsIndex);
                            yValue = xyds.getY(seriesIdx, itemsIndex);
                            if (xValue != null && yValue != null) {
                                writer.write(xValue.toString());
                                writer.write("\t");
                                writer.write(yValue.toString());
                                if (seriesIdx < seriesCount - 1) {
                                    writer.write("\t");
                                }
                            }
                        }
                    }
                    writer.newLine();
                }
            }
        } catch (ClassCastException e) { //else instanceof CategoryPlot
            log.info("Due to a caught class cast exception, it should be a CategoryPlot");
            CategoryPlot cp = chart.getCategoryPlot();
            String header = "# CategoryRowKey \t CategoryColumnKey \t CategoryRowIndex \t CategoryColumnIndex \t Value";
            writer.write(header);
            writer.newLine();
            for (int i = 0; i < cp.getDatasetCount(); i++) {
                CategoryDataset cpds = cp.getDataset(i);
                for (int rowIndex = 0; rowIndex < cpds.getRowCount(); rowIndex++) {
                    for (int columnIndex = 0; columnIndex < cpds.getColumnCount(); columnIndex++) {
                        Number value = cpds.getValue(rowIndex, columnIndex);
                        writer.write(cpds.getRowKey(rowIndex).toString());
                        writer.write("\t");
                        writer.write(cpds.getColumnKey(columnIndex).toString());
                        writer.write("\t");
                        writer.write(Integer.toString(rowIndex));
                        writer.write("\t");
                        writer.write(Integer.toString(columnIndex));
                        writer.write("\t");
                        writer.write(value.toString());
                        writer.newLine();
                    }
                }
            }

        }
        writer.close();
        log.info("Chart data written to: " + filename);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:entity.files.SYSFilesTools.java

/**
 * Standard Druck Routine. Nimmt einen HTML Text entgegen und ffnet den lokal installierten Browser damit.
 * Erstellt temporre Dateien im temp Verzeichnis opde<irgendwas>.html
 *
 * @param html/*from  w w w .j a  v  a2 s .c  om*/
 * @param addPrintJScript Auf Wunsch kann an das HTML automatisch eine JScript Druckroutine angehangen werden.
 */
public static File print(String html, boolean addPrintJScript) {
    File temp = null;
    try {
        // Create temp file.
        temp = File.createTempFile("opde", ".html");

        String text = "<html><head>";
        if (addPrintJScript) {
            text += "<script type=\"text/javascript\">" + "window.onload = function() {" + "window.print();"
                    + "}</script>";
        }
        text += OPDE.getCSS();
        text += "</head><body>" + SYSTools.htmlUmlautConversion(html) + "<hr/>" + "<div id=\"fonttext\">"
                + "<b>" + SYSTools.xx("misc.msg.endofreport") + "</b><br/>"
                + (OPDE.getLogin() != null ? SYSTools.htmlUmlautConversion(OPDE.getLogin().getUser().getUID())
                        : "")
                + "<br/>" + DateFormat.getDateTimeInstance().format(new Date()) + "<br/>"
                + OPDE.getAppInfo().getProgname() + ", v" + OPDE.getAppInfo().getVersion() + "/"
                + OPDE.getAppInfo().getBuildnum() + "</div></body></html>";

        // Write to temp file
        BufferedWriter out = new BufferedWriter(new FileWriter(temp));
        out.write(text);

        out.close();
        SYSFilesTools.handleFile(temp, Desktop.Action.OPEN);
    } catch (IOException e) {
        OPDE.error(e);
    }
    return temp;
}

From source file:Main.java

public static void visitRecursively(Node node, BufferedWriter bw) throws Exception {
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        // get child node
        Node childNode = list.item(i);
        if (childNode.getNodeType() == Node.TEXT_NODE) {
            System.out.println("Found Node: " + childNode.getNodeName() + " - with value: "
                    + childNode.getNodeValue() + " Node type:" + childNode.getNodeType());

            String nodeValue = childNode.getNodeValue();
            nodeValue = nodeValue.replace("\n", "").replaceAll("\\s", "");
            if (!nodeValue.isEmpty()) {
                System.out.println(nodeValue);
                bw.write(nodeValue);
                bw.newLine();/*  w  w w .j  a v a 2  s.co m*/
            }
        }
        visitRecursively(childNode, bw);
    }
}

From source file:com.clutch.ClutchSync.java

public static void sync(ClutchStats clutchStats) {
    if (thisIsHappening) {
        return;//from ww w  .  java  2 s  . c  o m
    }
    thisIsHappening = true;
    if (pendingReload) {
        pendingReload = false;
        for (ClutchView clutchView : clutchViews) {
            clutchView.contentChanged();
        }
    }
    ClutchAPIClient.callMethod("sync", null, new ClutchAPIResponseHandler() {
        @Override
        public void onSuccess(JSONObject response) {
            final AssetManager mgr = context.getAssets();

            File parentCacheDir = context.getCacheDir();
            final File tempDir;
            try {
                tempDir = File.createTempFile("clutchtemp", Long.toString(System.nanoTime()), parentCacheDir);
                if (!tempDir.delete()) {
                    Log.e(TAG, "Could not delete temp file: " + tempDir.getAbsolutePath());
                    return;
                }
                if (!tempDir.mkdir()) {
                    Log.e(TAG, "Could not create temp directory: " + tempDir.getAbsolutePath());
                    return;
                }
            } catch (IOException e) {
                Log.e(TAG, "Could not create temp file");
                return;
            }

            File cacheDir = getCacheDir();
            if (cacheDir == null) {
                try {
                    if (!copyAssetDir(mgr, tempDir)) {
                        return;
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Couldn't copy the asset dir files to the temp dir: " + e);
                    return;
                }
            } else {
                try {
                    if (!copyDir(cacheDir, tempDir)) {
                        return;
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Couldn't copy the cache dir files to the temp dir: " + e);
                    return;
                }
            }

            conf = response.optJSONObject("conf");
            String version = "" + conf.optInt("_version");
            newFilesDownloaded = false;
            try {
                JSONCompareResult confCompare = JSONCompare.compareJSON(ClutchConf.getConf(), conf,
                        JSONCompareMode.NON_EXTENSIBLE);
                if (confCompare.failed()) {
                    newFilesDownloaded = true;
                    // This is where in the ObjC version we write out the conf, but I don't think we need to anymore
                }
            } catch (JSONException e1) {
                Log.i(TAG, "Couldn't compare the conf file with the cached conf file: " + e1);
            }

            File cachedFiles = new File(tempDir, "__files.json");
            JSONObject cached = null;
            if (cachedFiles.exists()) {
                StringBuffer strContent = new StringBuffer("");
                try {
                    FileInputStream in = new FileInputStream(cachedFiles);
                    int ch;
                    while ((ch = in.read()) != -1) {
                        strContent.append((char) ch);
                    }
                    in.close();
                    cached = new JSONObject(new JSONTokener(strContent.toString()));
                } catch (IOException e) {
                    Log.e(TAG, "Could not read __files.json from cache file: " + e);
                } catch (JSONException e) {
                    Log.e(TAG, "Could not parse __files.json from cache file: " + e);
                }
            }
            if (cached == null) {
                cached = new JSONObject();
            }

            final JSONObject files = response.optJSONObject("files");
            try {
                JSONCompareResult filesCompare = JSONCompare.compareJSON(cached, files,
                        JSONCompareMode.NON_EXTENSIBLE);
                if (filesCompare.passed()) {
                    complete(tempDir, files);
                    return;
                }
            } catch (JSONException e1) {
                Log.i(TAG, "Couldn't compare the file hash list with the cached file hash list: " + e1);
            }

            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(cachedFiles));
                bw.write(files.toString());
                bw.flush();
                bw.close();
            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }

            currentFile = 0;
            final int numFiles = files.length();
            Iterator<?> it = files.keys();
            while (it.hasNext()) {
                final String fileName = (String) it.next();
                final String hash = files.optString(fileName);
                final String prevHash = cached.optString(fileName);

                // If they equal, then just continue
                if (hash.equals(prevHash)) {
                    if (++currentFile == numFiles) {
                        complete(tempDir, files);
                        return;
                    }
                    continue;
                }

                // Looks like we've seen a new file, so we should reload when this is all done
                newFilesDownloaded = true;

                // Otherwise we need to download the new file
                ClutchAPIClient.downloadFile(fileName, version, new ClutchAPIDownloadResponseHandler() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            File fullFile = new File(tempDir, fileName);
                            fullFile.getParentFile().mkdirs();
                            fullFile.createNewFile();
                            BufferedWriter bw = new BufferedWriter(new FileWriter(fullFile));
                            bw.write(response);
                            bw.flush();
                            bw.close();
                        } catch (IOException e) {
                            final Writer result = new StringWriter();
                            final PrintWriter printWriter = new PrintWriter(result);
                            e.printStackTrace(printWriter);
                            Log.e(TAG, "Tried, but could not write file: " + fileName + " : " + result);
                        }

                        if (++currentFile == numFiles) {
                            complete(tempDir, files);
                            return;
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String content) {
                        final Writer result = new StringWriter();
                        final PrintWriter printWriter = new PrintWriter(result);
                        e.printStackTrace(printWriter);
                        Log.e(TAG, "Error downloading file from server: " + fileName + " " + result + " "
                                + content);
                        if (++currentFile == numFiles) {
                            complete(tempDir, files);
                            return;
                        }
                    }
                });
            }
        }

        @Override
        public void onFailure(Throwable e, JSONObject errorResponse) {
            Log.e(TAG, "Failed to sync with the Clutch server: " + errorResponse);
        }
    });
    background(clutchStats);
}

From source file:eu.itesla_project.eurostag.EurostagImpactAnalysis.java

private static void dumpLimits(EurostagDictionary dictionary, BufferedWriter writer, String branchId,
        CurrentLimits cl1, CurrentLimits cl2, float nominalV1, float nominalV2) throws IOException {
    writer.write(dictionary.getEsgId(branchId));
    writer.write(";");
    writer.write(Float.toString(cl1 != null ? cl1.getPermanentLimit() : Float.MAX_VALUE));
    writer.write(";");
    writer.write(Float.toString(cl2 != null ? cl2.getPermanentLimit() : Float.MAX_VALUE));
    writer.write(";");
    writer.write(Float.toString(nominalV1));
    writer.write(";");
    writer.write(Float.toString(nominalV2));
    writer.write(";");
    writer.write(branchId);/*from ww w. j  av  a 2  s . c o  m*/
    writer.newLine();
}

From source file:emperior.Main.java

public static void copyFile(String filePath, File targetLocation) throws Exception {
    File f = new File(filePath);
    if (f.isFile()) {

        targetLocation.mkdirs();//from w  w  w  .j a v  a 2  s  .c o  m

        System.out.println(filePath);

        //         String [] pathElements = filePath.split("/");
        //         String [] pathElements = filePath.split("\\\\|/");
        String[] pathElements = filePath.split("\\\\");

        //         if(pathElements.length > 0){
        //            System.out.println("[test] " + targetLocation + File.separator + filePath.substring(0, filePath.lastIndexOf(System.getProperty("file.separator"))));
        //            targetLocation = new File(targetLocation + File.separator + filePath.substring(0, filePath.lastIndexOf(System.getProperty("file.separator"))));
        //            targetLocation.mkdirs();
        //         }

        JEditorPane editor = mainFrame.editors.get(filePath);

        String copypath = targetLocation + File.separator + pathElements[pathElements.length - 1];

        System.out.println("[test] " + copypath);

        Main.addLineToLogFile("[File] saving to: " + copypath);

        FileWriter fstream = new FileWriter(copypath);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(editor.getText());
        // Close the output stream
        out.close();

    }

}

From source file:com.idiro.utils.db.mysql.MySqlUtils.java

public static boolean importTable(JdbcConnection conn, String tableName, Map<String, String> features,
        File fileIn, File tablePath, char delimiter, boolean header) {
    boolean ok = true;
    try {/*w  w  w.jav a  2  s.c o  m*/
        DbChecker dbCh = new DbChecker(conn);
        if (!dbCh.isTableExist(tableName)) {
            logger.debug("The table which has to be imported has not been created");
            logger.debug("Creation of the table");
            Integer ASCIIVal = (int) delimiter;
            String[] options = { ASCIIVal.toString(), tablePath.getCanonicalPath() };
            conn.executeQuery(new MySqlBasicStatement().createExternalTable(tableName, features, options));
        } else {
            //Check if it is the same table 
            if (!dbCh.areFeaturesTheSame(tableName, features.keySet())) {
                logger.warn("Mismatch between the table to import and the table in the database");
                return false;
            }

            logger.warn("Have to check if the table is external or not, I do not know how to do that");

        }
    } catch (SQLException e) {
        logger.debug("Fail to watch the datastore");
        logger.debug(e.getMessage());
        return false;
    } catch (IOException e) {
        logger.warn("Fail to get the output path from a File object");
        logger.warn(e.getMessage());
        return false;
    }

    //Check if the input file has the right number of field
    FileChecker fChIn = new FileChecker(fileIn);
    FileChecker fChOut = new FileChecker(tablePath);
    String strLine = "";
    try {

        if (fChIn.isDirectory() || !fChIn.canRead()) {
            logger.warn("The file " + fChIn.getFilename() + "is a directory or can not be read");
            return false;
        }
        BufferedReader br = new BufferedReader(new FileReader(fileIn));
        //Read first line
        strLine = br.readLine();
        br.close();
    } catch (IOException e1) {
        logger.debug("Fail to open the file" + fChIn.getFilename());
        return false;
    }

    if (StringUtils.countMatches(strLine, String.valueOf(delimiter)) != features.size() - 1) {
        logger.warn("File given does not match with the delimiter '" + delimiter
                + "' given and the number of fields '" + features.size() + "'");
        return false;
    }

    BufferedWriter bw = null;
    BufferedReader br = null;

    try {
        bw = new BufferedWriter(new FileWriter(tablePath));
        logger.debug("read the file" + fileIn.getAbsolutePath());
        br = new BufferedReader(new FileReader(fileIn));
        String delimiterStr = "" + delimiter;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            bw.write("\"" + strLine.replace(delimiterStr, "\",\"") + "\"\n");
        }
        br.close();

        bw.close();
    } catch (FileNotFoundException e1) {
        logger.error(e1.getCause() + " " + e1.getMessage());
        logger.error("Fail to read " + fileIn.getAbsolutePath());
        ok = false;
    } catch (IOException e1) {
        logger.error("Error writting, reading on the filesystem from the directory" + fChIn.getFilename()
                + " to the file " + fChOut.getFilename());
        ok = false;
    }

    return ok;
}

From source file:net.iharding.utils.FileUtils.java

/**
 * /*w ww . j a  v a2s .  co  m*/
 * @param content
 * @param filePath
 */
public static void writeFile(String content, String filePath) {
    try {
        if (FileUtils.createFile(filePath)) {
            //            FileWriter fileWriter = new FileWriter(filePath, true);
            //            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            //???
            OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(content);
            bufferedWriter.close();
            fileWriter.close();
        } else {
            log.info("??");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:data_gen.Data_gen.java

public static void generate_xml() {
    SchemaGenerator schema = new SchemaGenerator(schema_fields);
    try {/*www. jav a  2s .com*/

        String content = schema.generateSchema();

        File file = new File(output_dir + "/" + "schema.xml");

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

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

    } catch (IOException e) {
        System.out.println("There was an error writing to the xml file." + "\n");
    }

}