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:gov.nih.nci.restgen.util.GeneratorUtil.java

public static void writeFile(String _outputDir, String _fileName, String _content) {
    BufferedWriter bufferedWriter = null;

    try {/*from w ww . j ava 2 s  . co m*/
        createOutputDir(_outputDir);
        File file = new File(_outputDir, _fileName);
        FileWriter fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(_content);
        bufferedWriter.flush();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (bufferedWriter != null) {
            try {
                bufferedWriter.close();
            } catch (Throwable t) {
            }
        }
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.ExtractDataAndQueryAsSparseVectors.java

private static void outputVector(BufferedWriter out, TrulySparseVector v) throws IOException {
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < v.mIDs.length; ++i) {
        if (i > 0)
            sb.append(' ');
        sb.append(v.mIDs[i]);/*from w w  w. jav  a2  s .co m*/
        sb.append(':');
        sb.append(v.mVals[i]);
    }
    String res = sb.toString().trim();
    if (!res.isEmpty()) {
        out.write(res);
        out.newLine();
    }
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static HttpURLConnection doRequest(String endpoint, CypherSession session, String[] keys,
        String[] values) throws IOException {
    HttpURLConnection connection = (java.net.HttpURLConnection) new URL(DOMAIN + endpoint).openConnection();
    connection.setDoOutput(true);/*from  ww w  . j ava 2s . c  o  m*/
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    connection.connect();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
    if (session != null) {
        writer.write("userID=");
        writer.write(session.getUser().getUserID() + "&sessionID=");
        writer.write(session.getSessionID());
    }
    if (keys != null && keys.length > 0) {
        if (session != null) {
            writer.write('&');
        }
        // write first row
        writer.write(keys[0]);
        writer.write('=');
        writer.write(URLEncoder.encode(values[0], "UTF-8"));
        for (int i = 1; i < keys.length; i++) {
            writer.write('&');
            writer.write(keys[i]);
            writer.write('=');
            writer.write(URLEncoder.encode(values[i], "UTF-8"));
        }
    }
    writer.close();
    return connection;
}

From source file:Main.java

public static void writeInteractionInFile(Context context, String startTime, String endTime, long duration,
        String filename) throws IOException, Exception {

    BufferedWriter writer = null;
    //String path="sdcard/LifeTracker/lifetracker.csv";
    File dir = new File("sdcard/SleepLog");
    boolean flag = dir.mkdir();
    //Log.d("Directory created?",""+flag);
    File file = new File(dir.getAbsolutePath(), filename);
    if (file.exists() == false) {
        //                  Intent service = new Intent(context,DataBaseService.class);
        //                  context.startService(service);
        file.createNewFile();//from ww w.j  a v a2  s .  c  o  m
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.write("Start Time,End Time,Duration");
        writer.newLine();
        writer.write(startTime + "," + endTime + "," + duration);
    } else {
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.newLine();
        writer.write(startTime + "," + endTime + "," + duration);
    }
    Log.d("Appended", "True");
    writer.flush();
    writer.close();

}

From source file:com.hazelcast.simulator.utils.FileUtils.java

public static void writeText(String text, File file) {
    if (text == null) {
        throw new NullPointerException("text can't be null");
    }/*from   ww  w  . j av a 2s . c o  m*/

    if (file == null) {
        throw new NullPointerException("file can't be null");
    }

    FileOutputStream stream = null;
    OutputStreamWriter streamWriter = null;
    BufferedWriter writer = null;
    try {
        stream = new FileOutputStream(file);
        streamWriter = new OutputStreamWriter(stream);
        writer = new BufferedWriter(streamWriter);
        writer.write(text);
        writer.close();
    } catch (IOException e) {
        throw new FileUtilsException(e);
    } finally {
        closeQuietly(writer);
        closeQuietly(streamWriter);
        closeQuietly(stream);
    }
}

From source file:madkitgroupextension.export.Export.java

public static void saveAndIncrementBuild() throws IOException {
    MadKitGroupExtension.VERSION.setBuildNumber(MadKitGroupExtension.VERSION.getBuildNumber() + 1);
    FileWriter fw = new FileWriter(new File("build.txt"));
    BufferedWriter b = new BufferedWriter(fw);
    b.write(Integer.toString(MadKitGroupExtension.VERSION.getBuildNumber()));
    b.flush();//from   ww w .  jav  a  2s.  co  m
    b.close();
    fw.close();
}

From source file:com.github.DroidPHP.ServerUtils.java

final private static void restoreConfiguration(String fileName) {

    File isConf = new File(getHttpDirectory() + "/conf/" + fileName);
    if (!isConf.exists()) {

        try {/*  w  ww  .  j  av  a  2  s  . co  m*/

            String mString;

            java.io.InputStream mStream = mContext.getAssets().open(fileName, AssetManager.ACCESS_BUFFER);

            java.io.BufferedWriter outputStream = new java.io.BufferedWriter(
                    new java.io.FileWriter(getHttpDirectory() + "/tmp/" + fileName));

            int c;
            while ((c = mStream.read()) != -1) {
                outputStream.write(c);
            }
            outputStream.close();
            mStream.close();

            mString = org.apache.commons.io.FileUtils
                    .readFileToString(new File(getHttpDirectory() + "/tmp/" + fileName), "UTF-8");

            mString = mString.replace("%app_dir%", getAppDirectory());
            mString = mString.replace("%http_dir%", getHttpDirectory());
            mString = mString.replace("%port%", serverPort);
            org.apache.commons.io.FileUtils
                    .writeStringToFile(new File(getHttpDirectory() + "/conf/" + fileName), mString, "UTF-8");
        } catch (java.lang.Exception e) {
            Log.e(TAG, "Unable to copy " + fileName + " from assets", e);

        }
    }

}

From source file:com.google.dart.tools.core.utilities.io.FileUtilities.java

/**
 * Overwrite the contents of the given file to the given contents.
 * /*from  w ww .j  a  v a2s . c  o  m*/
 * @param file the file whose contents are to be written
 * @param contents the new contents for the file
 * @throws IOException if the file contents could not be written
 */
public static void setContents(File file, String contents) throws IOException {
    FileWriter fileWriter = null;
    BufferedWriter writer;

    try {
        fileWriter = new FileWriter(file);
        writer = new BufferedWriter(fileWriter);
        writer.write(contents);
        writer.flush();
    } finally {
        if (fileWriter != null) {
            fileWriter.close();
        }
    }
}

From source file:edu.iu.daal_naive.NaiveUtil.java

static void generateTestPoints(int numOfDataPoints, int vectorSize, int nClasses, String localInputDir,
        FileSystem fs, Path dataDir) throws IOException, InterruptedException, ExecutionException {

    // Check data directory
    if (fs.exists(dataDir)) {
        fs.delete(dataDir, true);//from  w  ww  .  java 2  s  .  c om
    }
    // Check local directory
    File localDir = new File(localInputDir);
    // If existed, regenerate data
    if (localDir.exists() && localDir.isDirectory()) {
        for (File file : localDir.listFiles()) {
            file.delete();
        }
        localDir.delete();

    }
    boolean success = localDir.mkdir();
    if (success) {
        System.out.println("Directory: " + localInputDir + " created");
    }

    // generate test points
    BufferedWriter writer = new BufferedWriter(new FileWriter(localInputDir + File.separator + "testdata"));
    Random random = new Random();

    double point = 0;
    int label = 0;
    for (int i = 0; i < numOfDataPoints; i++) {
        for (int j = 0; j < vectorSize; j++) {
            point = random.nextDouble() * 2 - 1;
            writer.write(String.valueOf(point));
            writer.write(",");
        }

        label = random.nextInt(nClasses);
        writer.write(String.valueOf(label));
        writer.newLine();
    }

    writer.close();
    System.out.println("Write test data file");

    // Wrap to path object
    Path localInput = new Path(localInputDir);
    fs.copyFromLocalFile(localInput, dataDir);

}

From source file:de.uzk.hki.da.metadata.XmpCollector.java

/**
 * Collect./*from  ww w .ja va2  s . c  om*/
 *
 * @param xmpFiles list of xmp files to collect
 * @param targetFile the target file
 * @throws IOException 
 */
public static void collect(WorkArea wa, List<DAFile> xmpFiles, File targetFile) throws IOException {

    Model model = ModelFactory.createDefaultModel();

    for (DAFile dafile : xmpFiles) {

        File file = wa.toFile(dafile);

        logger.debug("collecting XMP file {}", file.getAbsolutePath());

        StringWriter xmpWriter = new StringWriter();

        try {
            // preprocess xmp in order to make it RDF/XML compatible   
            BufferedReader reader = new BufferedReader(new FileReader(file));
            BufferedWriter writer = new BufferedWriter(xmpWriter);

            logger.debug("Read the xmp file...");
            String currentLine;
            while ((currentLine = reader.readLine()) != null) {
                String trimmedLine = currentLine.trim();
                if (trimmedLine.startsWith("<?xpacket"))
                    continue;
                if (trimmedLine.contains("x:xmpmeta"))
                    continue;
                writer.write(currentLine);
            }
            reader.close();
            writer.close();

        } catch (Exception e) {
            throw new RuntimeException("Unable to preprocess XMP file: " + file.getAbsolutePath(), e);
        }

        final String baseName = FilenameUtils.removeExtension(file.getName());
        String[] list = file.getParentFile().list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                String baseName2 = FilenameUtils.removeExtension(name);
                if (baseName.equals(baseName2) && !name.toLowerCase().endsWith(".xmp"))
                    return true;
                else
                    return false;
            }
        });
        if (list.length > 1) {
            logger.warn("More than one matching file for sidecar file {}. Skipping ...", file.getName());
            continue;
        } else if (list.length < 1) {
            logger.warn("No matching file for sidecar file {}. Skipping ...", file.getName());
            continue;
        }

        logger.debug("found matching file {}", list[0]);
        // read XMP with matching file as base name
        // use "http://www.danrw.de/temp/" as a pseudo base URI in order to allow relative resource URIs
        model.read(new StringReader(xmpWriter.toString().trim().replaceFirst("^([\\W]+)<", "<")),
                "http://www.danrw.de/temp/" + list[0]);
    }
    FileOutputStream targetStream = null;
    try {
        targetStream = new FileOutputStream(targetFile);
        model.write(targetStream, "RDF/XML-ABBREV", "http://www.danrw.de/temp/");
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Could not write XMP collection file: " + targetFile.getAbsolutePath());
    } finally {
        if (targetStream != null) {
            targetStream.close();
        }
    }

}