File IO流

RandomAccessFile:

按照指针读取

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 + "]";
    }
}

1.字符流

Reader:

1.File文件关联

2.创建Reader阅读器

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

4.close阅读器和流

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关闭阅读器
    }
}

Write:

1.File文件关联

2.创建Write编写器

3.write方法工作 写入文件

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

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();
    }
}

文件,内容复制

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();
    }
}

LineNumberReader:

读取行号的包装流

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);
        }
    }
}

2.字节流

fileinputstream对应的byte[]

inputstreamreader对应的char[]

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

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]);
            }
        }

    }
}

3.包装流

简单包装流读写文件

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();
    }

}

DataStream:

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

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;
    }
}

ObjectStream:

按照对象读写数据

一定要实现对象的序列化

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;
    }
}

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

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();
    }

}

时间: 2024-11-09 00:43:51

File IO流的相关文章

Java基础知识强化之IO流笔记17:FileOutputStream构造方法使用

1. 可以参照之前写的笔记:   Android(java)学习笔记167:Java中操作文件的类介绍(File + IO流) 2. FileOutputStream(常用的)构造方法: FileOutputStream(File file)           Constructs a new FileOutputStream on the File file. FileOutputStream(String filename)           Constructs a new FileO

IO流和File

读键盘数据.显示数据6-1)io流的分类 按方向:输入流(读取数据) 输出流(写入数据) 按数据类型:字节流(基本数据类型)输出输入 字符流(字节流的包装 对字节流进行处理)输出输入四个核心类: InputStream 字节输入流 OutStream 字节输出流 Reader 字符输入流 Writer 字符输出流6-2) 文件类 File d:/lxj/xx.txt 绝对路径 构造方法: File(String dir,String fileName) File(String path)//pa

java IO流技术 之 File

IO流技术 概念:input - output 输入输出流: 输入:将文件读到内存中: 输出:将文件从内存中写出到其他地方 作用:主要就是解决设备和设备之间的数据传输问题. File :文件类的使用十分重要 (一)file的构造方法 1 public static void test1(){ 2 3 //三种拼接路径方式 4 //1.直接拼接 5 File filePath = new File("C:\\123\\aaa"); 6 System.out.println("是

IO流,File类的测试........课堂加总结

package liu0926; import java.io.File; import java.io.IOException; public class Text01 { public static void main(String[] args) { //IO流,File类的测试 //实例化某个文件的file对象 File file =new File("d:/text.txt"); //判断目标是否存在 if(file.exists()) { System.out.printl

详谈JAVA中的file类与IO流

File类 位置于java.io包构造方法:File(String parent, String child)new file("d:\\","a.txt") File(String pathname) new file("d:\\a.txt") File(File parent, String child)File f = new File("d:\\");File f1=new File(f,"a.txt&quo

小项目:mini资源管理器【使用IO流:包含(Directory与DirectoryInfo、File与FileInfo的用法)】

主界面是这样的 1.在点击查询引发的事件时把TextBox.Text输入的目录地址加载到TreeList控件里. private void btnSelect_Click(object sender, EventArgs e) { //避免重复加载tv.Nodes.Clear(); ////Load事件手动添加根节点TreeNode tn = new TreeNode(); tn.Text = tbxName.Text;//根节点名字:tn.Tag = tbxName.Text;//根节点物理地

IO流学习笔记1——File类

Java的IO支持通过java.io包下的类和接口来支持,在java.io包下主要包括输入.输出两种IO流,每种输入.输出流又可以分为字节流和字符流两大类.其中字节流以字节为单位,来处理输入.输出操作,而字符流则以字符来处理输入.输出操作.除此之外,Java的IO流使用了一种装饰器设计模式,它将IO流分成底层节点流和上层处理流,其中节点流用于和底层物理存储节点直接关联--不同物理节点获取节点流的方式可能存在一定的差异,但程序可以把不同的物理节点流包装成统一的处理流,从而允许程序使用统一的输入.输

Java学习总结(7)——(File类,IO流,(缓冲流,转换流等),Properties类)

一.File类 java.io.File类代表系统文件(文件和目录) 访问文件属性步骤 (1)创建文件对象 格式:File file=new File(String pathname); (2)调用方法:操作文件目录的属性(路径,权限,日期和时间等) File类的属性(separator默认名称分隔符) (1)在UNIX系统上,此字段的值为 '/ ';在window系统上,它为'\' (2)为了程序的跨平台性,文件的路径应该用这个属性值来代表 File类的常用方法 方法名称 说明 Boolean

乐字节Java之file、IO流基础知识和操作步骤

嗨喽,小乐又来了,今天要给大家送上的技术文章是Java重点知识-IO流. 先来看看IO流的思维导图吧. 一. File 在Java中,Everything is Object!所以在文件中,也不例外!在Java中,可以用 File类来表示一个与硬盘上文件联系!!!注意: 1.File仅代表一个联系,可能文件存在,也可能不存在: 2.这里的文件可以是文件,也可以是文件夹: 在常用类中已经详细讲过File,此处不在讲解 二. IO流 1.流概念 流即流动.流向,从一端流向另一端.如水流:从山里流向到