Java File文件的读写

FileInputStream:

该流可以从文件中读取数据,它的对象可以用new创建。

使用字符串类型的文件名创建一个输入流对象读取文件:

InputStream f = new FileInputStream("c:/java/hello");

也可以使用一个文件对象来创建一个输入流对象读取文件,首先要用File()方法来创建一个文件对象:

File f = new File("c:/java/hello");
InputStream out = new File InputStream(f);

FileOutputStream的创建方法类似.(如果文件不存在则会创建该文件)

两个类的综合实例:

package some;
import java.io.*;

public class some{
    public static void main(String[] args) {
        try {
            byte bWrtie[] = {11,21,3,40,5};
            OutputStream os = new FileOutputStream("test.txt");
            for (int x = 0; x < bWrtie.length; x++) {
                os.write(bWrtie[x]);
            }
            os.close();
            
            InputStream is = new FileInputStream("test.txt");
            int size = is.available();
            for (int i = 0; i < size; i++) {
                System.out.print((char)is.read()+"  ");
            }
            is.close();
        } catch (IOException e) {
            // TODO: handle exception
            System.out.println("Exception");
        }
    }
}

由于文件写入的时候使用的是二进制格式所以输出会有乱码,解决方案:

package some;
import java.io.*;

public class some{
    public static void main(String[] args) throws IOException {
        File f = new File("a.txt");
        FileOutputStream fop = new FileOutputStream(f);
        OutputStreamWriter writer = new OutputStreamWriter(fop,"gbk");
        writer.append("中文输入");
        writer.append("\r\n");// /r/n是常用的换行转义字符,有的编译器不认识/n
        writer.append("English");
        writer.close();//关闭写入流,同时把缓冲区的内容写到文件里
        fop.close();//关闭输出流
        FileInputStream fip =new FileInputStream(f);
        InputStreamReader reader = new InputStreamReader(fip,"gbk");
        StringBuffer s = new StringBuffer();
        while (reader.ready()) {
            s.append((char) reader.read());
        }
        System.out.println(s.toString());
        reader.close();
        fip.close();
    }
}

ByteArrayInputStream类:

创建方式:

//用接受字节数组作为参数
ByteArrayInputStream bArray = new ByteArrayInputStream(byte[] a);
/*用一个接受字节数字和两个整形变量off、len。前者表示第一个读取的字节,len表示读取字节的长度*/
ByteArrayInputStream bArray = new ByteArrayInputStream(byte[] a, int off, int len);

ByteArrayOutputStream类的创建类似

猜你喜欢

转载自www.cnblogs.com/MXming/p/13399674.html