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

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

Description

write Text

Declaration

public static void writeText(File file, String text) 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);//from  w w w . j  a  v a  2 s .c  om
    }

    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. writeString(String string, File file, boolean append)
  2. writeStringToFile(String content, String fileName)
  3. writeStringToFile(String content, String fileName, boolean append)
  4. writeStringToFile(String string, File file)
  5. writeStringToFile(String stringToWrite, String filename)
  6. writeText(File file, String text, String charsetName)
  7. writeTextFile(String path, String text)
  8. writeTextFile(String string, String fileName)
  9. writeTextToFile(String file, String text)