Write a string value into the specified file. - Android File Input Output

Android examples for File Input Output:InputStream

Description

Write a string value into the specified file.

Demo Code


//package com.java2s;

import java.io.Closeable;

import java.io.DataOutputStream;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    /**//from ww w .  j  av  a2 s.  co  m
     * Write a string value into the specified file.
     * 
     * @param path
     *            The target file
     * @param data
     *            The string value
     * @throws IOException
     */
    public static void writeString(final File file, final String data)
            throws IOException {
        writeString(file.getAbsolutePath(), data);
    }

    /**
     * Write a string value into the specified path.
     * 
     * @param path
     *            The target file path
     * @param data
     *            The string value
     * @throws IOException
     */
    public static void writeString(final String path, final String data)
            throws IOException {
        DataOutputStream dos = null;

        try {
            dos = new DataOutputStream(new FileOutputStream(path));
            dos.writeBytes(data);
            dos.flush();
        } finally {
            closeQuietly(dos);
        }
    }

    /**
     * Close the closeables quietly
     * 
     * @param closeables
     *            Instances of {@link Closeable}
     */
    public static void closeQuietly(final Closeable... closeables) {
        if (null == closeables || closeables.length <= 0)
            return;

        for (int i = 0; i < closeables.length; i++) {
            final Closeable closeable = closeables[i];
            if (null == closeable)
                continue;

            try {
                closeables[i].close();
            } catch (IOException e) {
            }
        }
    }
}

Related Tutorials