Java读取和写入文本文件内容

1、Java 写入文本文件源码

 

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter; 

public class TxtWriter { 

    public static void appendToFile(String content, File file) throws IOException {
        TxtWriter.appendToFile(content, file, System.getProperty("file.encoding"));
    }
    public static void appendToFile(String content, File file, String encoding) throws IOException {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), encoding));
            writer.write(content);
        } finally {
         if (writer != null)

                writer.close();

        }
    } 
 

    public static void saveToFile(String content, File file) throws IOException {

        TxtWriter.saveToFile(content, file, System.getProperty("file.encoding"));
    } 
 

    public static void saveToFile(String content, File file, String encoding) throws IOException {

        BufferedWriter writer = null;

        try {

            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), encoding));

            writer.write(content);

        } finally {

            if (writer != null)

                writer.close();

        }
    }
}

  2、Java 读取文本文件源码

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader; 
 

public class TxtReader { 
 
    /**
     * 从文件中读取文本内容, 读取时使用平台默认编码解码文件中的字节序列
     * @param file 目标文件
     * @return
     * @throws IOException
     */
    public static String loadStringFromFile(File file) throws IOException {
        return TxtReader.loadStringFromFile(file, System.getProperty("file.encoding"));
    } 
 

    /**
     * 从文件中读取文本内容
    * @param file 目标文件
     * @param encoding 目标文件的文本编码格式
     * @return
     * @throws IOException
     */
    public static String loadStringFromFile(File file, String encoding) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
            StringBuilder builder = new StringBuilder();
            char[] chars = new char[4096];

            int length = 0;

            while (0 < (length = reader.read(chars))) {

                builder.append(chars, 0, length);

            }

            return builder.toString();

        } finally {

            try {

                if (reader != null) reader.close();

            } catch (IOException e) {

                throw new RuntimeException(e);

            }

        }

    } 
}

  转载自:http://www.appfen.com/2012/java-input-output-txt.html


posted @ 2012-02-29 13:45  月亮的影子  阅读(4643)  评论(0编辑  收藏  举报