IO流读取、写入文件

package test;
// IO 流读取、写入文件
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestFile {

    public static void main(String[] args) throws Exception {
        String path = "src\\test.docx";
        writeContent(path);
        System.out.println(readFromFile(path));
    }

    public static void writeContent(String path) throws IOException {
        for (int i = 0; i < 100; i++) {
            writeToFile(path, "hello world! ( " + i + " )\n");
        }
        writeToFile(path, " ");
    }

    /**
     * DOC 从文件里读取数据.
     * 
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static String readFromFile(String path)
            throws FileNotFoundException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(new File(path))));
        StringBuffer line = new StringBuffer();
        String str = null;
        while ((str = br.readLine()) != null) {
            line.append(str + "\n");
        }
        return line.toString();
    }

    /**
     * DOC 往文件里写入数据.
     * 
     * @throws IOException
     */
    private static void writeToFile(String path, String content)
            throws IOException {
        File file = new File(path);// 要写入的文本文件
        if (!file.exists()) {// 如果文件不存在,则创建该文件
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file, true);// 获取该文件的输出流
        // true 表示在末尾添加
        writer.write(content);// 写内容
        writer.flush();// 清空缓冲区,立即将输出流里的内容写到文件里
        writer.close();// 关闭输出流,释放资源
    }

}


你可能感兴趣的:(java,读取文件,IO流)