Example usage for java.io BufferedWriter BufferedWriter

List of usage examples for java.io BufferedWriter BufferedWriter

Introduction

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

Prototype

public BufferedWriter(Writer out) 

Source Link

Document

Creates a buffered character-output stream that uses a default-sized output buffer.

Usage

From source file:com.legstar.codegen.CodeGenMakeTest.java

/**
 * Check controls on input make file tag <cixstarget>.
 * @throws IOException if file cannot be read
 *//*  w  ww  .  j a  v  a2s .  c o m*/
public void testCodeGenMakeNoTargetTag() throws IOException {
    File tempMakeFile = File.createTempFile("test-temp", "xml");
    /* Create a temporary make file */
    BufferedWriter out;
    out = new BufferedWriter(new FileWriter(tempMakeFile));
    out.write("<somethingElse/>");
    out.close();

    CodeGenMake codeGenMake = new CodeGenMake();
    codeGenMake.setModelName("modelName");
    codeGenMake.setModel("model");
    codeGenMake.setCodeGenMakeFileName(tempMakeFile.getPath());
    try {
        codeGenMake.execute();
    } catch (RuntimeException e) {
        assertEquals("Empty or invalid code generation make file", e.getMessage());
    }
}

From source file:com.vmanolache.mqttpolling.Polling.java

private void sendPost() throws UnsupportedEncodingException, JSONException {
    try {//from w w w.  ja  v a  2  s. c  o  m
        String url = "http://localhost:8080/notifications";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");

        /**
         * POSTing *
         */
        OutputStream os = connection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery()); // should be fine if my getQuery is encoded right yes?
        writer.flush();
        writer.close();
        os.close();
        connection.connect();

        int status = connection.getResponseCode();
        System.out.println(status);
    } catch (IOException ex) {
        Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.yata.core.FileManager.java

public static BufferedWriter getFileWriter(String fileName) throws IOException {

    System.out.println("getFileWriter@" + className + " : File to write in :-> " + fileName);

    File file = new File(fileName);

    // if file doesnt exists, then create it
    if (!file.exists()) {
        file.createNewFile();//from w  w w  .j  a va2 s.  c  om
    }

    FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

    return bufferedWriter;
}

From source file:com.eufar.asmm.server.DownloadFunction.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("DownloadFunction - the function started");
    ServletContext context = getServletConfig().getServletContext();
    request.setCharacterEncoding("UTF-8");
    String dir = context.getRealPath("/tmp");
    ;//from w w w  . ja v a2  s.  c o  m
    String filename = "";
    File fileDir = new File(dir);
    try {
        System.out.println("DownloadFunction - create the file on server");
        filename = request.getParameterValues("filename")[0];
        String xmltree = request.getParameterValues("xmltree")[0];

        // format xml code to pretty xml code
        Document doc = DocumentHelper.parseText(xmltree);
        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        format.setIndentSize(4);
        XMLWriter xw = new XMLWriter(sw, format);
        xw.write(doc);

        Writer out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(dir + "/" + filename), "UTF-8"));
        out.append(sw.toString());
        out.flush();
        out.close();
    } catch (Exception ex) {
        System.out.println("ERROR during rendering: " + ex);
    }
    try {
        System.out.println("DownloadFunction - send file to user");
        ServletOutputStream out = response.getOutputStream();
        File file = new File(dir + "/" + filename);
        String mimetype = context.getMimeType(filename);
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Pragma", "private");
        response.setHeader("Cache-Control", "private, must-revalidate");
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int length;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            out.write(bbuf, 0, length);
        }
        in.close();
        out.flush();
        out.close();
        FileUtils.cleanDirectory(fileDir);
    } catch (Exception ex) {
        System.out.println("ERROR during downloading: " + ex);
    }
    System.out.println("DownloadFunction - file ready to be donwloaded");
}

From source file:com.textocat.textokit.morph.commons.TrainingDataWriterBase.java

@Override
public void initialize(UimaContext ctx) throws ResourceInitializationException {
    super.initialize(ctx);
    ///* w ww  .j a v  a 2 s  .  co  m*/
    File outputFile = new File(outputDir, TRAINING_DATA_FILENAME);
    try {
        OutputStream os = FileUtils.openOutputStream(outputFile);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "utf-8"));
        outputWriter = new PrintWriter(bw);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:it.gmariotti.android.example.parser.json.WriteJsonGsonActivity.java

@SuppressLint("WorldReadableFiles")
@SuppressWarnings("deprecation")
private void writeJson() {

    String jsonString = JsonHelper.writeGson();
    Log.i(TAG, jsonString);/*from  w  ww .ja  v  a  2 s .com*/

    BufferedWriter writer = null;
    try {

        // Use MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE only for test
        writer = new BufferedWriter(
                new OutputStreamWriter(openFileOutput("jsonfile", MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE)));
        writer.write(jsonString);
        writer.close();

        // Update ui
        if (jsonView != null)
            jsonView.setText(jsonString);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.iisigroup.cap.report.AbstractReportHtmlService.java

@Override
public ByteArrayOutputStream generateReport(Request request) throws CapException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = null;//from  w  ww. j a  v  a 2 s  .  co  m
    OutputStreamWriter wr = null;
    try {
        Template t = getFmConfg().getConfiguration().getTemplate(getReportDefinition() + REPORT_SUFFIX);
        Map<String, Object> reportData = execute(request);
        wr = new OutputStreamWriter(out,
                getSysConfig().getProperty(ReportParamEnum.defaultEncoding.toString(), DEFAULT_ENCORDING));
        writer = new BufferedWriter(wr);
        t.process(reportData, writer);
    } catch (Exception e) {
        if (e.getCause() != null) {
            throw new CapException(e.getCause(), e.getClass());
        } else {
            throw new CapException(e, e.getClass());
        }
    } finally {
        IOUtils.closeQuietly(wr);
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(out);
    }
    return out;
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.geneExpression.SetSubjectsIdListener.java

@Override
public void handleEvent(Event event) {
    // TODO Auto-generated method stub
    Vector<String> values = this.setSubjectsIdUI.getValues();
    Vector<String> samples = this.setSubjectsIdUI.getSamples();
    for (String v : values) {
        if (v.compareTo("") == 0) {
            this.setSubjectsIdUI.displayMessage("All identifiers have to be set");
            return;
        }// www .j  a  va 2  s . c om
    }

    File file = new File(this.dataType.getPath().toString() + File.separator
            + this.dataType.getStudy().toString() + ".subject_mapping.tmp");
    try {
        FileWriter fw = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fw);
        out.write(
                "study_id\tsite_id\tsubject_id\tSAMPLE_ID\tPLATFORM\tTISSUETYPE\tATTR1\tATTR2\tcategory_cd\n");

        File stsmf = ((GeneExpressionData) this.dataType).getStsmf();
        if (stsmf == null) {
            for (int i = 0; i < samples.size(); i++) {
                out.write(this.dataType.getStudy().toString() + "\t" + "\t" + values.elementAt(i) + "\t"
                        + samples.elementAt(i) + "\t" + "\t" + "\t" + "\t" + "\t" + "\n");
            }
        } else {
            try {
                BufferedReader br = new BufferedReader(new FileReader(stsmf));
                String line = br.readLine();
                while ((line = br.readLine()) != null) {
                    String[] fields = line.split("\t", -1);
                    String sample = fields[3];
                    String subject;
                    if (samples.contains(sample)) {
                        subject = values.get(samples.indexOf(sample));
                    } else {
                        br.close();
                        return;
                    }
                    out.write(fields[0] + "\t" + fields[1] + "\t" + subject + "\t" + sample + "\t" + fields[4]
                            + "\t" + fields[5] + "\t" + fields[6] + "\t" + fields[7] + "\t" + fields[8] + "\n");
                }
                br.close();
            } catch (Exception e) {
                this.setSubjectsIdUI.displayMessage("File error: " + e.getLocalizedMessage());
                out.close();
                e.printStackTrace();
            }
        }
        out.close();
        try {
            File fileDest;
            if (stsmf != null) {
                String fileName = stsmf.getName();
                stsmf.delete();
                fileDest = new File(this.dataType.getPath() + File.separator + fileName);
            } else {
                fileDest = new File(this.dataType.getPath() + File.separator
                        + this.dataType.getStudy().toString() + ".subject_mapping");
            }
            FileUtils.moveFile(file, fileDest);
            ((GeneExpressionData) this.dataType).setSTSMF(fileDest);
        } catch (IOException ioe) {
            this.setSubjectsIdUI.displayMessage("File error: " + ioe.getLocalizedMessage());
            return;
        }
    } catch (Exception e) {
        this.setSubjectsIdUI.displayMessage("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
    this.setSubjectsIdUI.displayMessage("Subject to sample mapping file updated");
    WorkPart.updateSteps();
    WorkPart.updateFiles();
    UsedFilesPart.sendFilesChanged(dataType);
}

From source file:Main.java

public static void server2mobile(Context context, String type) {

    String serverPath = "http://shaunrain.zicp.net/FileUp/QueryServlet?type=" + type;
    try {//from  www . j  av a2 s .co m
        URL url = new URL(serverPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("GET");

        int code = conn.getResponseCode();
        Log.d("code", code + "");
        if (code == 200) {
            InputStream is = conn.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            conn.disconnect();

            String result = new String(baos.toByteArray());
            String[] results = result.split("[$]");
            for (String r : results) {
                if (r.length() != 0) {
                    URL json = new URL(r);
                    HttpURLConnection con = (HttpURLConnection) json.openConnection();
                    con.setConnectTimeout(5000);
                    con.setRequestMethod("GET");
                    int co = con.getResponseCode();
                    if (co == 200) {
                        File jsonFile;
                        if (r.endsWith("clear.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/clear.json");
                        } else if (r.endsWith("crowd.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/crowd.json");
                        } else if (r.endsWith("trouble.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/trouble.json");
                        } else {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/control.json");
                        }

                        if (jsonFile.exists())
                            jsonFile.delete();
                        jsonFile.createNewFile();
                        try (BufferedReader reader = new BufferedReader(
                                new InputStreamReader(con.getInputStream(), "gb2312"));
                                BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile));) {
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                writer.write(line);
                            }
                        }

                    }
                    con.disconnect();
                }
            }

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:edu.harvard.iq.dataverse.dataaccess.FileAccessIOTest.java

@Before
public void setUpClass() throws IOException {
    dataverse = MocksFactory.makeDataverse();
    dataset = MocksFactory.makeDataset();
    dataset.setOwner(dataverse);/* w  w  w .  j  av  a2 s  .c om*/
    dataset.setAuthority("tmp");
    dataset.setIdentifier("dataset");
    dataset.setStorageIdentifier("Dataset");

    dataFile = MocksFactory.makeDataFile();
    dataFile.setOwner(dataset);
    dataFile.setStorageIdentifier("DataFile");

    datasetAccess = new FileAccessIO<>(dataset);
    dataFileAccess = new FileAccessIO<>(dataFile);
    dataverseAccess = new FileAccessIO<>(dataverse);

    File file = new File("/tmp/files/tmp/dataset/Dataset");
    file.getParentFile().mkdirs();
    file.createNewFile();
    new File("/tmp/files/tmp/dataset/DataFile").createNewFile();
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
        bw.write("This is a test string");
    }
}