码迷,mamicode.com
首页 > 其他好文 > 详细

File IO流

时间:2014-08-28 14:44:49      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   java   使用   io   strong   

RandomAccessFile:

按照指针读取

bubuko.com,布布扣
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * RandomAccessFile 使用范例
 * 
 */
public class RandomAccessFileDemo {

    public static void main(String[] args) throws Exception {
        Person[] persons = new Person[] { new Person("one", 25, true),
                new Person("two", 26, false), new Person("three", 27, true),
                new Person("four", 28, false) };
        write(persons);
        Person p = read(2);//读取第三个
        System.out.println(p);
    }

    private static List<Long> pointer;

    private static void write(Person[] persons) throws Exception {
        File _file = new File("data/store.dat");
        if (!_file.exists()) {
            File dir = _file.getParentFile();
            dir.mkdir();
        }
        RandomAccessFile file = new RandomAccessFile("data/store.dat", "rw");
        pointer = new ArrayList<Long>();
        for (Person p : persons) {
            pointer.add(file.getFilePointer());//指针 每个对象头指针放在arraylist中
            file.writeUTF(p.name);
            System.out.println("name: " + file.getFilePointer());
            file.writeInt(p.age);
            System.out.println("age: " + file.getFilePointer());
            file.writeBoolean(p.sex);
            System.out.println("sex: " + file.getFilePointer());
        }
        file.close();
    }

    private static Person read(int i) throws Exception {
        RandomAccessFile file = new RandomAccessFile("data/store.dat", "rw");
        Long l = pointer.get(i);
        file.skipBytes(Integer.parseInt(String.valueOf(l)));
        //file.seek(l);
        Person p = new Person();
        p.name=file.readUTF();//顺序一定要一致
        p.age=file.readInt();
        p.sex=file.readBoolean();
        file.close();//不关闭 读入不会错 写入会报错啊
        return p;
    }
}

class Person {
    String name;
    int age;
    boolean sex;

    public Person() {
    }

    public Person(String name, int age, boolean sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Person [age=" + age + ", name=" + name + ", sex=" + sex + "]";
    }
}
View Code

1.字符流

bubuko.com,布布扣bubuko.com,布布扣

Reader:

1.File文件关联

2.创建Reader阅读器

3.reader方法工作 读出全部文件

4.close阅读器和流

bubuko.com,布布扣
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

public class ReaderDemo {
    public static void main(String[] args) throws Exception {
        // 编码
        // byte[] byets;
        // String str=new String(byets, "utf-8");
        // byets[] bytes=str.getBytes("utf-8");

        File file = new File("src/ReaderDemo.java");// 1文件关联
        Reader reader = new FileReader(file);// 2创建阅读器
        // int i = reader.read();// 读取单个字符
        // System.out.println(i);
        int i;
        char[] array = new char[200];
        // //3reader方法工作 读出全部文件
        // while (true) {
        // i = reader.read(array);
        // if (i == -1) {
        // break;
        // }
        // for (int j = 0; j < i; j++) {
        // System.out.print(array[j]);
        // }
        // }

        // 读出全部文件
        int len = -1;
        while ((len = reader.read(array, 0, array.length)) != -1) {
            for (int j = 0; j < len; j++) {
                System.out.print(array[j]);
            }

        }
        reader.close();// 4关闭阅读器
    }
}
View Code

Write:

1.File文件关联

2.创建Write编写器

3.write方法工作 写入文件

4.flush缓存和close编写器,流

bubuko.com,布布扣
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Scanner;

public class WriteDemo {
    public static void main(String[] args) throws Exception {
        System.out.println("需要创建什么文件:");
        Scanner scanner = new Scanner(System.in);
        String filename = scanner.nextLine();
        // 1文件关联
        File file = new File(filename);
        // 2创建编写器
        Writer writer = new FileWriter(file);
        System.out.println("输入你需要的内容:");
        while (true) {
            String content = scanner.nextLine();
            if (content.length() == 0) {
                break;
            }
            // 3write方法工作 文件写入
            writer.write(content);
            writer.write("\r\n");
        }
        writer.flush();
        // 4关闭编写器
        writer.close();
    }
}
View Code

 

文件,内容复制

bubuko.com,布布扣
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;

//文件复制类
public class CopyContentDemo {
    public static void main(String[] args) throws Exception {
        //内容复制
        File inputfile = new File("src/CopyContentDemo.java");
        File outfile = new File("outfile.java");
        Reader reader = new FileReader(inputfile);
        Writer writer = new FileWriter(outfile);
        // int i;
        // char[] carray = new char[200];
        // while (true) {
        // i = reader.read(carray);
        // if (i == -1) {
        // break;
        // }
        // for (int j = 0; j < i; j++) {
        // writer.write(carray[j]);
        // }
        // }
        int len = -1;
        char[] date = new char[200];
        while ((len = reader.read(date, 0, date.length)) != -1) {
            writer.write(date, 0, len);
        }
        System.out.println("数据复制成功!");
        reader.close();
        writer.flush();
        writer.close();
    }
}
View Code

LineNumberReader:

读取行号的包装流

bubuko.com,布布扣
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.LineNumberReader;

//读取行号的包装流
public class LineNumberReaderDemo {
    public static void main(String[] args) throws Exception {
        File file = new File("src/LineNumberReaderDemo.java");
        // 包装流读取全文件
        LineNumberReader reader = new LineNumberReader(new FileReader(file));
        String s;
        while ((s = reader.readLine()) != null) {
            System.out.print(reader.getLineNumber() + ":    ");
            System.out.println(s);
        }
    }
}
View Code

 

2.字节流

bubuko.com,布布扣

bubuko.com,布布扣bubuko.com,布布扣

fileinputstream对应的byte[]

inputstreamreader对应的char[]

都是整形int时候为-1判断

bubuko.com,布布扣
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class CharsetDemo {
    // 字节流练习
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        error("txt/a.txt");
        System.out.println("--------------------------------------");
        right("txt/a.txt", "GBK");
    }

    public static void error(String filepath) throws Exception {
        File file = new File(filepath);
        // //1.BufferedReader包装流实现
        // BufferedReader reader = new BufferedReader(new FileReader(file));
        // String s;
        // while ((s = reader.readLine()) != null) {
        // System.out.println(s);
        // }

        // //2.BufferedInputStream包装流实现
        // BufferedInputStream bis=new BufferedInputStream(new
        // FileInputStream(file));
        // int i;
        // while ((i=bis.read())!=-1) {
        // System.out.print((char)i);
        // }

        // 3.FileInputStream字节流实现
        FileInputStream fis = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        int len = -1;
        while ((len = fis.read(bytes, 0, bytes.length)) != -1) {
            // String s=new String(bytes);
            String s = new String(bytes, "UTF-8");// 解决乱码
            System.out.println(s);
        }

    }

    public static void right(String filepath, String charset) throws Exception {
        File file = new File(filepath);
        InputStreamReader isr = new InputStreamReader(new BufferedInputStream(
                new FileInputStream(file)), charset);
        char[] array = new char[50];
        int i = -1;
        while ((i = isr.read(array)) != -1) {
            for (int j = 0; j < i; j++) {
                System.out.print(array[j]);
            }
        }

    }
}
View Code

 

3.包装流

bubuko.com,布布扣

简单包装流读写文件

 

bubuko.com,布布扣
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;

public class BufferedDemo {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        // 系统文件目录
        String dir = System.getProperty("user.dir");
        File infile = new File(dir + "/src/kbstream/BufferedDemo.java");
        File outfile = new File("txt/out.txt");
        BufferedReader in = new BufferedReader(new FileReader(infile));
        BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
        String line;
        while ((line = in.readLine()) != null) {
            out.write(line);
            out.write("\r\n");
        }
        in.close();
        out.flush();
        out.close();
    }

}
View Code

 

DataStream:

按照特定的数据类型读写数据

bubuko.com,布布扣
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DataStreamDemo {
    final public static String FILENAME = "txt/data.dat";

    // 按照特定的数据类型读写数据
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        Person[] persons = { new Person("zhang", 40, true),
                new Person("li", 14, false) };
        WriteToFile(persons);
        // persons = ReaderFromFile();
        // for (Person p : persons) {
        // System.out.println(p);
        // }
        // 输出集合内容
        System.out.println(Arrays.toString(persons));
    }

    private static void WriteToFile(Person[] persons) throws Exception {
        File file = new File(FILENAME);
        //两次用了包装流 就为了放缓存区 性能高效
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(
                new FileOutputStream(file)));
        for (Person p : persons) {
            dos.writeUTF(p.name);
            dos.writeInt(p.age);
            dos.writeBoolean(p.sex);
        }
        dos.flush();
        dos.close();
    }

    private static Person[] ReaderFromFile() throws Exception {
        File file = new File(FILENAME);
        DataInputStream dis = new DataInputStream(new BufferedInputStream(
                new FileInputStream(file)));
        List<Person> list = new ArrayList<Person>();
        try {
            while (true) {
                Person p = new Person();
                p.name = dis.readUTF();
                p.age = dis.readInt();
                p.sex = dis.readBoolean();
                list.add(p);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        }
        dis.close();
        // 集合转换成数组 参数 new Person[0]只是为了确定数组类型
        return list.toArray(new Person[0]);
    }

}

class Person {
    String name;
    int age;
    boolean sex;

    public Person() {
        // TODO Auto-generated constructor stub
    }

    public Person(String name, int age, boolean sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Person:  name: " + name + "  age: " + age + "  sex: " + sex;
    }
}
View Code

ObjectStream:

按照对象读写数据

一定要实现对象的序列化

bubuko.com,布布扣
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ObjectStreamDemo {
    final public static String FILENAME = "txt/object.dat";

    // objectstream 一定要实现序列化
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        Human[] humans = { new Human("zhang", 14, true),
                new Human("li", 40, false) };
        writeToFile(humans);
        humans = readFromFile();
        System.out.println(Arrays.toString(humans));
    }

    public static void writeToFile(Human[] humans) throws Exception {
        File file = new File(FILENAME);
        ObjectOutputStream oos = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream(file)));
        for (Human h : humans) {
            oos.writeObject(h);
        }
        oos.flush();
        oos.close();
    }

    public static Human[] readFromFile() throws Exception {
        File file = new File(FILENAME);
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
                new FileInputStream(file)));
        List<Human> list = new ArrayList<Human>();
        try {
            while (true) {
                //一个一个对象读取的 也可以判断是否为null再list添加的
                Human human = (Human) ois.readObject();
                list.add(human);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block

        }
        ois.close();
        return list.toArray(new Human[0]);
    }
}

class Human implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -6916114420631083299L;
    String name;
    int age;
    boolean sex;

    public Human() {
        // TODO Auto-generated constructor stub
    }

    public Human(String name, int age, boolean sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Human:  name: " + name + "  age: " + age + "  sex: " + sex;
    }
}
View Code

实现音频视频等二进制文件复制

 

bubuko.com,布布扣
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileCopyDemo {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        String dir = System.getProperty("user.dir");
        File infile = new File(dir + "/txt/love你.mp3");
        String outfilepath = "D:/txt/love你.mp3";
        createFileAndDir(outfilepath);
        File outfile = new File(outfilepath);
        // 因为针对二进制文件 所以要用字节流
        // 1.效率低
        // FileInputStream in=new FileInputStream(infile);
        // FileOutputStream out=new FileOutputStream(outfile);
        // 2.包装流 效率高
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                infile));
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(outfile));
        byte[] c = new byte[4096];
        int len = -1;
        while ((len = in.read(c, 0, c.length)) != -1) {
            out.write(c, 0, len);
        }
        // 用字符流只能copy大小 "内容"无法完成编码 mp3放不出来
        // BufferedReader in = new BufferedReader(new FileReader(infile));
        // BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
        // String line;
        // while ((line = in.readLine()) != null) {
        // out.write(line);
        // out.write("\r\n");
        // }
        System.out.println("copy ok!");
        in.close();
        out.flush();
        out.close();
    }

    private static void createFileAndDir(String filepath) throws Exception {
        File file = new File(filepath);
        if (file.exists()) {
            return;
        }
        File dir = file.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        file.createNewFile();
    }

}
View Code

 

bubuko.com,布布扣

 

File IO流

标签:style   blog   http   color   os   java   使用   io   strong   

原文地址:http://www.cnblogs.com/manusas/p/3941506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!