日期:2014-05-20  浏览次数:20716 次

文件流读写的小问题,在线等
BufferedReader
InputStreamReader
FileInputStream
DataInputStream
OutputStreamWriter

1 这几个类有什么区别呢,分别怎么用呢,

2 现我想向 D:\demosun\demosu.txt 这文件中写入一行文字,怎么实现呢
3 现我想把 D:\demosun\demosu.txt 这文件中的内容读出来 怎么实现呢
thanks

------解决方案--------------------
具体怎么用你好好去看看API手册,帮你写了个例子。
Java code

package com.study.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ReadAndWriteFile {

    public static void main(String[] args) {
        //写文件
        writeFile("文件路径", "文件内容");
        //读文件
        readFile("文件路径");
    }
    
    public static void readFile(String path){
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(""));
            while(true){
                String line = reader.readLine();
                if(line == null){
                    break;
                }
                System.out.println(line + "\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void writeFile(String path, String content){
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(""));
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

------解决方案--------------------
原理:http://www.iteye.com/topic/313635
实践:http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html