Android Text File Write writeText(File file, String text, String charsetName)

Here you can find the source of writeText(File file, String text, String charsetName)

Description

write Text

Declaration

public static void writeText(File file, String text, String charsetName)
            throws IOException 

Method Source Code

//package com.java2s;
import java.io.BufferedWriter;

import java.io.File;

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

public class Main {
    public static void writeText(File file, String text) throws IOException {
        writeText(file, text, null);// w ww  .  j av  a  2s  . com
    }

    public static void writeText(File file, String text, String charsetName)
            throws IOException {
        byte[] bytes = charsetName == null ? text.getBytes() : text
                .getBytes(charsetName);
        writeBytes(file, false, bytes);
    }

    /**
     * write text, make every line starts with prefix
     * @param bw
     * @param text
     * @param prefix
     * @throws IOException
     * @see Properties
     */
    public static void writeText(BufferedWriter bw, String text,
            String prefix) throws IOException {
        int len = text.length();
        int current = 0;
        int last = 0;
        while (current < len) {
            char c = text.charAt(current);
            if (c == '\n' || c == '\r') {
                if (last != current)
                    bw.write(prefix + text.substring(last, current));
                bw.newLine();
                last = current + 1;
            }
            current++;
        }
        if (last != current)
            bw.write(prefix + text.substring(last, current));
        bw.flush();
    }

    /**
     * write bytes into file
     * @param file
     * @param append
     * @param bytes
     * @throws IOException
     */
    public static void writeBytes(File file, boolean append, byte[] bytes)
            throws IOException {
        if (bytes.length == 0)
            return;

        FileOutputStream output = new FileOutputStream(file, append);
        output.write(bytes);
        output.flush();
        output.close();
    }
}

Related

  1. writeStringToFile(String content, String fileName)
  2. writeStringToFile(String content, String fileName, boolean append)
  3. writeStringToFile(String string, File file)
  4. writeStringToFile(String stringToWrite, String filename)
  5. writeText(File file, String text)
  6. writeTextFile(String path, String text)
  7. writeTextFile(String string, String fileName)
  8. writeTextToFile(String file, String text)
  9. writeToFile(File file, String content)