Java读写文本文件

1 字符输入(FileReader , char)

import java.io.IOException;
import java.io.FileReader;

public class ep10_1 {
    public static void main(String[] args) throws IOException{
        //引用对象b
        FileReader b = new FileReader("/tmp/ep10_1.txt");
        //定义文本存储的reader空间
        char[] a = new char[1000];
        //将对象b的内容读入a中,返回字符数
        int num = b.read(a);
        //将字符a转换成str输出
        String str = new String(a,0,num);
        System.out.println("文件读取内容为:\n"+str);
     b.close();
}
 }

 

2 字符输出(FileWrite char)

import java.io.FileWriter;
import java.io.IOException;


public class ep10_3 {
    public static void main(String[] args) {
        try{
            FileWriter a = new FileWriter("/tmp/wt.txt");
            for (int i=32;i<126;i++){
                //char类型写入
                a.write(i);
            }
            a.close();
        }catch (IOException e){}
    }
}

 3 字符输入输出(BufferedReader,BufferedWriter,char) 

import java.io.*;
import java.nio.Buffer;

public class ep10_4 {
    public static void main(String[] args) {
        String str = new String();
        try{
            //BufferedReader引用的类型为String,也就是说BufferedReader会把FileReader字符型的文本转换为String
        BufferedReader in = new BufferedReader(new FileReader("/tmp/ep10_1.txt"));
        BufferedWriter out = new BufferedWriter(new FileWriter("/tmp/ep10_4.txt"));
        while ((str=in.readLine())!=null) {
            System.out.println(str);
            out.write(str);
            out.newLine();
        }
        out.flush();
        in.close();
        out.close();
    }catch (IOException e){
            System.out.println("error contents:"+e);
        }
    }
}

4 字节的输入

 

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


public class ep10_5 {
    public static void main(String[] args) {
        try {
            byte[] bt = new byte[1000];
            FileInputStream ins = new FileInputStream("/tmp/ep10_1.txt");
            int num = ins.read(bt);
            String str = new String(bt,0,num);
            System.out.println("contents:\n"+str);

        }catch (IOException e){
            System.out.println("error:\n"+e);
        }

    }
}

 

 

posted @ 2015-07-15 23:52  李雷雷alexkn  阅读(352)  评论(0编辑  收藏  举报