Example usage for java.io BufferedWriter flush

List of usage examples for java.io BufferedWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.lazy.gank.logging.Logcat.java

/**
 * msg //w ww .jav  a  2s . co m
 *
 * @param msg
 * @param logFileName log ??
 */
private static void saveLog2File(String msg, String logFileName) {
    FileWriter objFilerWriter = null;
    BufferedWriter objBufferedWriter = null;

    do { // ???
        String state = Environment.getExternalStorageState();
        //  SD ?
        if (!Environment.MEDIA_MOUNTED.equals(state)) {
            Log.d(TAG, "Not mount SD card!");
            break;
        }

        // SD ???
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            Log.d(TAG, "Not allow write SD card!");
            break;
        }

        File rootPath = new File(sLogFolderPath);
        if (rootPath.exists()) {

            File fileLogFilePath = new File(sLogFolderPath, logFileName);
            // ?
            if (true != fileLogFilePath.exists()) {
                try {
                    fileLogFilePath.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }

            // ??
            if (true != fileLogFilePath.exists()) {
                Log.d(TAG, "Create log file failed!");
                break;
            }

            try {
                objFilerWriter = new FileWriter(fileLogFilePath, //
                        true); // ?
            } catch (IOException e1) {
                Log.d(TAG, "New FileWriter Instance failed");
                e1.printStackTrace();
                break;
            }

            objBufferedWriter = new BufferedWriter(objFilerWriter);

            try {
                objBufferedWriter.write(msg);
                objBufferedWriter.flush();
            } catch (IOException e) {
                Log.d(TAG, "objBufferedWriter.write or objBufferedWriter.flush failed");
                e.printStackTrace();
            }
        } else {
            Log.d(TAG, "Log savePaht invalid!");
        }

    } while (false);

    if (null != objBufferedWriter) {
        try {
            objBufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (null != objFilerWriter) {
        try {
            objFilerWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:gtu._work.etc.GoogleContactUI.java

void googleTableMouseClicked(MouseEvent evt) {
    try {/* w ww .j av a 2  s.c  om*/
        JPopupMenuUtil popupUtil = JPopupMenuUtil.newInstance(googleTable).applyEvent(evt);

        //CHANGE ENCODE
        popupUtil.addJMenuItem("set encode", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    String code = StringUtils.defaultString(JOptionPaneUtil.newInstance().iconPlainMessage()
                            .showInputDialog("input file encode", "ENCODE"), "UTF8");
                    encode = Charset.forName(code).displayName();
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
                System.err.println("encode : " + encode);
            }
        });

        //SIMPLE LOAD GOOGLE CSV FILE
        popupUtil.addJMenuItem("open Google CSV file", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = JFileChooserUtil.newInstance().selectFileOnly().addAcceptFile("csv", ".csv")
                        .showOpenDialog().getApproveSelectedFile();
                if (file == null) {
                    errorMessage("file is not correct!");
                    return;
                }
                try {
                    if (file.getName().endsWith(".csv")) {
                        DefaultTableModel model = (DefaultTableModel) googleTable.getModel();
                        LineNumberReader reader = new LineNumberReader(
                                new InputStreamReader(new FileInputStream(file), GOOGLE_CVS_ENCODE));
                        for (String line = null; (line = reader.readLine()) != null;) {
                            if (reader.getLineNumber() == 1) {
                                continue;
                            }
                            model.addRow(line.split(","));
                        }
                        reader.close();
                        googleTable.setModel(model);
                        JTableUtil.newInstance(googleTable).hiddenAllEmptyColumn();
                    }
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
            }
        });

        //SAVE CSV FILE FOR GOOGLE
        popupUtil.addJMenuItem("save to Google CVS file", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = JFileChooserUtil.newInstance().selectFileOnly().addAcceptFile(".csv", ".csv")
                        .showSaveDialog().getApproveSelectedFile();
                if (file == null) {
                    errorMessage("file is not correct!");
                    return;
                }
                file = FileUtil.getIndicateFileExtension(file, ".csv");
                try {
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(file), GOOGLE_CVS_ENCODE));
                    StringBuilder sb = new StringBuilder();
                    for (Object title : googleColumns) {
                        sb.append(title + ",");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    System.out.println(sb);
                    writer.write(sb.toString());
                    writer.newLine();
                    DefaultTableModel model = (DefaultTableModel) googleTable.getModel();
                    for (int row = 0; row < model.getRowCount(); row++) {
                        sb = new StringBuilder();
                        for (int col = 0; col < model.getColumnCount(); col++) {
                            String colVal = StringUtils.defaultString((String) model.getValueAt(row, col), "");
                            if (colVal.equalsIgnoreCase("null")) {
                                colVal = "";
                            }
                            sb.append(colVal + ",");
                        }
                        sb.deleteCharAt(sb.length() - 1);
                        System.out.println(sb);
                        writer.write(sb.toString());
                        writer.newLine();
                    }
                    writer.flush();
                    writer.close();
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
            }
        });

        //PASTE CLIPBOARD
        popupUtil.addJMenuItem("paste clipboard", new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
                JTableUtil.newInstance(googleTable).pasteFromClipboard_multiRowData(true);
            }
        });

        popupUtil.addJMenuItem("paste clipboard to selected cell", new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
                JTableUtil.newInstance(googleTable).pasteFromClipboard_singleValueToSelectedCell();
            }
        });

        JMenuItem addEmptyRowItem = JTableUtil.newInstance(googleTable).jMenuItem_addRow(false,
                "add row count?");
        addEmptyRowItem.setText("add row");
        JMenuItem removeColumnItem = JTableUtil.newInstance(googleTable).jMenuItem_removeColumn(null);
        removeColumnItem.setText("remove column");
        JMenuItem removeRowItem = JTableUtil.newInstance(googleTable).jMenuItem_removeRow(null);
        removeRowItem.setText("remove row");
        JMenuItem removeAllRowItem = JTableUtil.newInstance(googleTable)
                .jMenuItem_removeAllRow("remove all row?");
        removeAllRowItem.setText("remove all row");
        JMenuItem clearSelectedCellItem = JTableUtil.newInstance(googleTable)
                .jMenuItem_clearSelectedCell("are you sure clear selected area?");
        clearSelectedCellItem.setText("clear selected area");
        popupUtil.addJMenuItem(addEmptyRowItem, removeColumnItem, removeRowItem, removeAllRowItem,
                clearSelectedCellItem);
        popupUtil.show();
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

public String doRedirect(String urlRedirect, boolean useTim) {
    // android.os.Debug.waitForDebugger();
    try {//from  w ww. j av a2 s . co m
        // with server phpOIDC, check for '#'
        if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?"))
                || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) {
            String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&");
            String code = "";
            String state = "";
            String state_key = "state";
            for (int i = 0; i < params.length; i++) {
                String param = params[i];
                int idxEqual = param.indexOf('=');
                if (idxEqual >= 0) {
                    String key = param.substring(0, idxEqual);
                    String value = param.substring(idxEqual + 1);
                    if (key.startsWith("code"))
                        code = value;
                    if (key.startsWith("state"))
                        state = value;
                    if (key.startsWith("session_state")) {
                        state = value;
                        state_key = "session_state";
                    }
                }
            }

            // display code and state
            Logd(TAG, "doRedirect => code: " + code + " / state: " + state);

            // doRepost(code,state);
            if (code.length() > 0) {

                // get token_endpoint endpoint
                String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url);
                if (isEmpty(token_endpoint)) {
                    Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url);
                    return null;
                }

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                HttpURLConnection huc = getHUC(token_endpoint);
                huc.setInstanceFollowRedirects(false);

                if (useTim) {
                    if (mUsePrivateKeyJWT) {
                        nameValuePairs.add(new BasicNameValuePair("client_assertion_type",
                                "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
                        String client_assertion = secureStorage.getPrivateKeyJwt(token_endpoint);
                        Logd(TAG, "client_assertion: " + client_assertion);
                        nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion));
                    } else {
                        huc.setRequestProperty("Authorization",
                                "Basic " + secureStorage.getClientSecretBasic());
                    }
                } else {
                    String authorization = (mOcp.m_client_id + ":" + mOcp.m_client_secret);
                    authorization = Base64.encodeToString(authorization.getBytes(), Base64.DEFAULT);
                    huc.setRequestProperty("Authorization", "Basic " + authorization);
                }

                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                huc.setDoOutput(true);
                huc.setChunkedStreamingMode(0);

                OutputStream os = huc.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
                BufferedWriter writer = new BufferedWriter(out);

                nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
                nameValuePairs.add(new BasicNameValuePair("code", code));
                nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri));
                if (state != null && state.length() > 0)
                    nameValuePairs.add(new BasicNameValuePair(state_key, state));

                // write URL encoded string from list of key value pairs
                writer.write(getQuery(nameValuePairs));
                writer.flush();
                writer.close();
                out.close();
                os.close();

                Logd(TAG, "doRedirect => before connect");
                huc.connect();
                int responseCode = huc.getResponseCode();
                System.out.println("2 - code " + responseCode);
                Log.d(TAG, "doRedirect => responseCode " + responseCode);
                InputStream in = null;
                try {
                    in = new BufferedInputStream(huc.getInputStream());
                } catch (IOException ioe) {
                    sysout("io exception: " + huc.getErrorStream());
                }
                if (in != null) {
                    String result = convertStreamToString(in);
                    // now you have the string representation of the HTML request
                    in.close();

                    Logd(TAG, "doRedirect: " + result);

                    // save as static for now
                    return result;

                } else {
                    Logd(TAG, "doRedirect null");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.playframework.generator.mybatisplus.AutoGenerator.java

/**
 * Mapper/*from ww w.  j a v  a2 s.c  om*/
 *
 * @param beanName
 * @param mapperName
 * @throws IOException
 */
protected void buildMapper(String beanName, String mapperName) throws IOException {
    File mapperFile = new File(PATH_MAPPER, mapperName + ".java");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile), "utf-8"));
    bw.write("package " + config.getMapperPackage() + ";");
    bw.newLine();
    bw.newLine();
    bw.write("import " + config.getEntityPackage() + "." + beanName + ";");
    bw.newLine();
    bw.write("import com.baomidou.mybatisplus.mapper.BaseMapper;");
    bw.newLine();

    bw = buildClassComment(bw, beanName + " ??");
    bw.newLine();
    bw.write("public interface " + mapperName + " extends BaseMapper<" + beanName + "> {");
    bw.newLine();
    bw.newLine();

    // ----------mapperEnd----------
    bw.newLine();
    bw.write("}");
    bw.flush();
    bw.close();
}

From source file:org.apache.playframework.generator.mybatisplus.AutoGenerator.java

/**
 * XML/*  www.  j a v  a2 s  .co m*/
 *
 * @param beanName
 * @param columns
 * @param types
 * @param comments
 * @throws IOException
 */
protected void buildMapperXml(String beanName, List<String> columns, List<String> types, List<String> comments,
        Map<String, IdInfo> idMap, String mapperName, String mapperXMLName) throws IOException {
    File mapperXmlFile = new File(PATH_XML, mapperXMLName + ".xml");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperXmlFile)));
    bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    bw.newLine();
    bw.write(
            "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");
    bw.newLine();
    bw.write("<mapper namespace=\"" + config.getMapperPackage() + "." + mapperName + "\">");
    bw.newLine();
    bw.newLine();

    /*
     * ?SqlMapper
     */
    if (config.isResultMap()) {
        buildResultMap(bw, beanName, idMap, columns);
    } else {
        buildSQL(bw, idMap, columns);
    }

    bw.write("</mapper>");
    bw.flush();
    bw.close();
}

From source file:com.digitalpebble.behemoth.mahout.util.Mahout2LibSVM.java

public int run(String[] args) throws Exception {

    Options options = new Options();
    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();
    // create the parser
    CommandLineParser parser = new GnuParser();

    options.addOption("h", "help", false, "print this message");
    options.addOption("v", "vector", true, "input vector sequencefile");
    options.addOption("l", "label", true, "input vector sequencefile");
    options.addOption("o", "output", true, "output Behemoth corpus");

    // parse the command line arguments
    CommandLine line = null;//from w w  w  .ja v a 2s.  c o  m
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            formatter.printHelp("CorpusGenerator", options);
            return 0;
        }
        if (!line.hasOption("v") | !line.hasOption("o") | !line.hasOption("l")) {
            formatter.printHelp("CorpusGenerator", options);
            return -1;
        }
    } catch (ParseException e) {
        formatter.printHelp("CorpusGenerator", options);
    }

    Path vectorPath = new Path(line.getOptionValue("v"));
    Path labelPath = new Path(line.getOptionValue("l"));
    String output = line.getOptionValue("o");

    Path tempOutput = new Path(vectorPath.getParent(), "temp-" + System.currentTimeMillis());

    // extracts the string representations from the vectors
    int retVal = vectorToString(vectorPath, tempOutput);
    if (retVal != 0) {
        HadoopUtil.delete(getConf(), tempOutput);
        return retVal;
    }

    Path tempOutput2 = new Path(vectorPath.getParent(), "temp-" + System.currentTimeMillis());

    retVal = convert(tempOutput, labelPath, tempOutput2);

    // delete the temp output
    HadoopUtil.delete(getConf(), tempOutput);

    if (retVal != 0) {
        HadoopUtil.delete(getConf(), tempOutput2);
        return retVal;
    }

    // convert tempOutput to standard file
    BufferedWriter bow = new BufferedWriter(new FileWriter(new File(output)));

    // the label dictionary is not dumped to text
    int labelMaxIndex = 0;
    Map<String, Integer> labelIndex = new HashMap<String, Integer>();

    Configuration conf = getConf();
    FileSystem fs = FileSystem.get(conf);
    FileStatus[] fss = fs.listStatus(tempOutput2);
    try {
        for (FileStatus status : fss) {
            Path path = status.getPath();
            // skips the _log or _SUCCESS files
            if (!path.getName().startsWith("part-") && !path.getName().equals(tempOutput2.getName()))
                continue;
            SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf);
            // read the key + values in that file
            Text key = new Text();
            Text value = new Text();
            while (reader.next(key, value)) {
                String label = key.toString();
                // replace the label by its index
                Integer indexLabel = labelIndex.get(label);
                if (indexLabel == null) {
                    indexLabel = new Integer(labelMaxIndex);
                    labelIndex.put(label, indexLabel);
                    labelMaxIndex++;
                }
                String val = value.toString();
                bow.append(indexLabel.toString()).append(val).append("\n");
            }
            reader.close();
        }
        bow.flush();
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } finally {
        bow.close();
        fs.delete(tempOutput2, true);
    }
    return 0;
}

From source file:com.baomidou.mybatisplus.generator.AutoGenerator.java

/**
 * service//  www.j a  v  a  2s .  c om
 *
 * @param beanName
 * @param serviceName
 * @throws IOException
 */
protected void buildService(String beanName, String serviceName) throws IOException {
    File serviceFile = new File(PATH_SERVICE, serviceName + ".java");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(serviceFile), "utf-8"));
    bw.write("package " + config.getServicePackage() + ";");
    bw.newLine();
    bw.newLine();
    bw.write("import " + config.getEntityPackage() + "." + beanName + ";");
    bw.newLine();
    String superService = config.getSuperService();
    bw.write("import " + superService + ";");
    bw.newLine();

    bw = buildClassComment(bw, beanName + " ???");
    bw.newLine();
    superService = superService.substring(superService.lastIndexOf(".") + 1);
    bw.write("public interface " + serviceName + " extends " + superService + "<" + beanName + "> {");
    bw.newLine();
    bw.newLine();

    // ----------serviceEnd----------
    bw.newLine();
    bw.write("}");
    bw.flush();
    bw.close();
}

From source file:com.isencia.passerelle.hmi.HMIBase.java

public void saveModelAs(final CompositeActor model, final URL destinationURL)
        throws IOException, IllegalActionException, NameDuplicationException {
    File destinationFile = null;// www  .  j  av a 2 s  . c o  m

    try {
        destinationFile = getLocalFileFromURL(destinationURL);
    } catch (final Exception e) {
        // ignore, means that the URL is unknown or a remote model URL
        // this is handled further below
    }
    applyFieldValuesToParameters();
    if (destinationFile != null && (!destinationFile.exists() || destinationFile.canWrite())) {
        BufferedWriter outputWriter = null;
        try {
            outputWriter = new BufferedWriter(new FileWriter(destinationFile));
            // set name of the model with file name
            String newModelName = destinationFile.getName();
            if (newModelName.contains(".moml")) {
                newModelName = newModelName.replace(".moml", "");
            }
            model.setName(newModelName);
            model.exportMoML(outputWriter);
        } finally {
            if (outputWriter != null) {
                outputWriter.flush();
                outputWriter.close();
                this.setSaved();
            }
        }
    } else {
        throw new IOException("File not writable " + destinationFile);
    }

}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * Append passed in content to the file.
 * Create file if it does not exist.  // ww w .  j  av a  2s .  c om
 * Create the sub-directories if they do not exist.
 * 
 * @param file - file name with path
 * @param content - the content to append to the file
 */
public static void appendContentToFile(String file, String content) {

    if (file == null || file.length() <= 0) {
        throw new CompositeException("File path is not defined.");
    }

    // Create the sub-directories if they do not already exist
    String fileDir = getDirectory(file);
    if (fileDir != null && !fileExists(fileDir)) {
        mkdirs(fileDir);
    }
    // Write to the file
    BufferedWriter bw = null;
    try {
        if (file != null && file.trim().length() > 0) {
            bw = new BufferedWriter(new FileWriter(file, true));
            if (content != null && content.trim().length() > 0) {

                bw.write(content);
                bw.newLine();
                bw.flush();
            }
        }
    } catch (IOException e) {
        CompositeLogger.logException(e, "Could not append to file " + file);
        throw new ValidationException(e.getMessage(), e);
    } 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.smart.common.officeFile.CSVUtils.java

/**
 *
 * @param exportData ?/*from www  .j a  v  a  2s  .c  om*/
 * @param rowMapper ??
 * @param outPutPath 
 * @param filename ??
 * @return
 */
public static File createCSVFile(List exportData, LinkedHashMap rowMapper, String outPutPath, String filename) {

    File csvFile = null;
    BufferedWriter csvFileOutputStream = null;
    try {
        csvFile = new File(outPutPath + filename + ".csv");
        // csvFile.getParentFile().mkdir();
        File parent = csvFile.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        csvFile.createNewFile();

        // GB2312?","
        csvFileOutputStream = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
        // 
        for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator.hasNext();) {
            java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
            csvFileOutputStream.write("\"" + propertyEntry.getValue().toString() + "\"");
            if (propertyIterator.hasNext()) {
                csvFileOutputStream.write(",");
            }
        }
        csvFileOutputStream.newLine();

        // 
        for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
            LinkedHashMap row = (LinkedHashMap) iterator.next();
            System.out.println(row);

            for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) {
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                // System.out.println(BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
                csvFileOutputStream.write("\"" + propertyEntry.getValue().toString() + "\"");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
            }

            //                for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) {
            //                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
            //                    System.out.println(BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
            //                    csvFileOutputStream.write("\""
            //                            + BeanUtils.getProperty(row, propertyEntry.getKey().toString()) + "\"");
            //                    if (propertyIterator.hasNext()) {
            //                        csvFileOutputStream.write(",");
            //                    }
            //                }
            if (iterator.hasNext()) {
                csvFileOutputStream.newLine();
            }
        }
        csvFileOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            csvFileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return csvFile;
}