Java文件操作和IO流


File 类

File 类构造方法

image.png
File 的构造方法
image.png

File 类实例方法

image.png
image.png
image.png

image.png
image.png

File f1 = new File("E:\\Java_Learning\\0718\\src\\com\\xjt\\myFile\\java");
System.out.println(f1.isDirectory());   //true
System.out.println(f1.isFile());    //false
System.out.println(f1.exists());    //true
System.out.println(f1.getAbsolutePath());   //E:\Java_Learning\0718\src\com\xjt\myFile\java
System.out.println(f1.getPath());   //E:\Java_Learning\0718\src\com\xjt\myFile\java
System.out.println(f1.getName());   //java
String[] fileList = f1.list();
//System.out.println(fileList);   //[Ljava.lang.String;@10f87f48
for (String item: fileList) {
    System.out.println(item);   //java.txt  javase.txt  spring.md
}

File[] listFiles = f1.listFiles();
for (File file:listFiles) {
    System.out.println(file);  //E:\Java_Learning\0718\src\com\xjt\myFile\java\java.txt
    System.out.println(file.getName());     //java.txt
    if(file.isFile()){
        System.out.println(file+"-------"); //E:\Java_Learning\0718\src\com\xjt\myFile\java\java.txt-------
    }
}

递归

image.png
示例:递归求阶乘

public static long factorial(int n){
    if(n==1){
        return 1;
    }else{
        return n*factorial(n-1);
    }
}

示例:递归找目录下的所有文件
image.png
image.png

IO 流

image.png

字节流

image.png

FileOutputStream 字节流-写

构造方法:

//继承关系
java.lang.Object
	java.io.OutputStream
		java.io.FileOutputStream
//
FileOutputStream文件输出流是用于将数据写入FileFileDescriptor的输出流
构造器 描述
[FileOutputStream](#%3Cinit%3E(java.io.File))([File](File.html) file) 创建文件输出流以写入由指定的 File对象表示的文件。
[FileOutputStream](#%3Cinit%3E(java.io.File,boolean))([File](File.html) file, boolean append) 创建文件输出流以写入由指定的 File对象表示的文件。
[FileOutputStream](#%3Cinit%3E(java.lang.String))([String](../lang/String.html) name) 创建文件输出流以写入具有指定名称的文件。
[FileOutputStream](#%3Cinit%3E(java.lang.String,boolean))([String](../lang/String.html) name, boolean append) 创建文件输出流以附加的方式写入具有指定名称的文件。

注意:

FileOutputStream(String name) 底层其实也是FileOutputStream(File file) 传入一个File对象
public FileOutputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null, false);
    }

image.png
image.png
image.png
注意:用完文件句柄之后一定记得关掉,释放内存资源

public void close() throws IOException
关闭此文件输出流并释放与此流关联的所有系统资源。 > 此文件输出流可能不再用于写入字节。
image.png
image.png

FileInputStream 字节流-读

public class FileInputStreamextends InputStream

//FileInputStream从文件系统中的文件获取输入字节,要读取字符流,请考虑使用FileReader

构造方法:

构造器 描述
[FileInputStream](#%3Cinit%3E(java.io.File))([File](File.html) file) 通过打开与实际文件的连接来创建 FileInputStream ,该文件由文件系统中的 File对象 file命名。
[FileInputStream](#%3Cinit%3E(java.lang.String))([String](../lang/String.html) name) 通过打开与实际文件的连接来创建 FileInputStream ,该文件由文件系统中的路径名 name命名。

方法:

变量和类型 方法 描述
int [available](#available())() 返回可以从此输入流中读取(或跳过)的剩余字节数的估计值,而不会被下一次调用此输入流的方法阻塞。
void [close](#close())() 关闭此文件输入流并释放与该流关联的所有系统资源。
int [read](#read())() 从此输入流中读取一个字节的数据。
int [read](#read(byte%5B%5D))(byte[] b) 读字节数据存储到字节列表 b 中
int [read](#read(byte%5B%5D,int,int))(byte[] b, int off, int len) offset 是 从 指定的 索引位 开始 读取, len 是 读取的位数
long [skip](#skip(long))(long n) 跳过并从输入流中丢弃 n字节的数据。
FileInputStream fis = new FileInputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\aaa.txt");
//read():读取一个字节数据
//        int len = fis.read();       //h == 104
//        System.out.println(len);    //104

//read(byte[] b)
byte[] bys = new byte[5];
int len = fis.read(bys);
System.out.println(len);    //5
//System.out.println(new String(bys));    //hello
System.out.println(new String(bys,0,len));  ////hello

len = fis.read(bys);
System.out.println(len);    //5
//System.out.println(new String(bys));    //\r\nwor
System.out.println(new String(bys,0,len));  //\r\nwor

len = fis.read(bys);
System.out.println(len);    //2
//System.out.println(new String(bys));    //ldwor
System.out.println(new String(bys,0,len));  //ld

len = fis.read(bys);
System.out.println(len);    //-1
//System.out.println(new String(bys));    //ldwor
//System.out.println(new String(bys,0,len));  //StringIndexOutOfBoundsException

/*new String(bys) 当读取的长度不够bys.length时,会多读bys中的字符
         * bys = ['l','d','w','o','r']
         * String(byte[],int offset,int len)来控制 读取数组的位数。
         * offset 是从指定的索引位开始读取,
         * len 是 读取的位数,在这个例子中,最后一次读了2个字母,所以read(byte b)返回的值是2,然后存入len中
         * */

//释放资源
fis.close();

while 循环读取文件

FileInputStream fis = new FileInputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\aaa.txt");

byte[] bys = new byte[1024];    //1024及其整数倍
int len;
while ((len=fis.read(bys))!=-1){
    System.out.println(new String(bys, 0, len));
}
//释放资源
fis.close();

示例:
image.png

FileInputStream fis = new FileInputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\story.txt");
FileOutputStream fos = new FileOutputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\story2.txt");
byte[] bys = new byte[1024];    //1024及其整数倍
int len;
while ((len=fis.read(bys))!=-1){
    fos.write(bys,0,len);
}
fis.close();
fos.close();

案例:字节流复制图片
image.png

字节缓冲流-BufferOutputStream 和 BufferInputStream

image.png

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\aaa.txt",true));
bos.write("hello\r\n".getBytes());
bos.write("world\r\n".getBytes());
bos.write("china\r\n".getBytes());

bos.close();

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\story.txt"));
//一次读一个字节(中文会乱码)
//        int ch;
//        while ((ch=bis.read()) != -1){
//            System.out.println((char)ch);
//        }

//一次读一个字符数组长度(1024及其倍数)
int len;
byte[] bytes = new byte[1024];
while ((len=bis.read(bytes))!=-1){
    System.out.println(new String(bytes,0,len));
}
bis.close();

案例:拷贝视频
四种实现方法:

  • 基本字节流一次读取一个字节
  • 基本字节流一次读取一个字节数组
  • 字节缓冲流一次读取一个字节
  • 字节缓冲流一次读取一个字节数组
//开始时间
long start = System.currentTimeMillis();
copyVideo4();
long end = System.currentTimeMillis();
System.out.println("耗时:"+(end-start));


//方式1:基本字节流一次读取一个字节  耗时:199854
public static void copyVideo1() throws IOException {
    FileOutputStream fos = new FileOutputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\def.flv");
    FileInputStream fis = new FileInputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\abc.flv");
    int len;
    while ((len=fis.read())!=-1){
        fos.write(len);
    }
    fos.close();
    fis.close();
}
//方式2:基本字节流一次读取一个字节数组   耗时:281
public static void copyVideo2() throws IOException {
    FileOutputStream fos = new FileOutputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\def.flv");
    FileInputStream fis = new FileInputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\abc.flv");
    int len;
    byte[] bytes = new byte[1024];
    while ((len=fis.read(bytes))!=-1){
        fos.write(bytes,0,len);
    }
    fos.close();
    fis.close();
}
//方式3:字节缓冲流一次读取一个字节     耗时:280
public static void copyVideo3() throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\def.flv"));
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\abc.flv"));
    int len;
    while ((len=bis.read())!=-1){
        bos.write(len);
    }
    bos.close();
    bis.close();
}
//方式3:字节缓冲流一次读取一个字节数组   耗时:77
public static void copyVideo4() throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\def.flv"));
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\abc.flv"));
    int len;
    byte[] bytes = new byte[1024];
    while ((len=bis.read(bytes))!=-1){
        bos.write(bytes,0,len);
    }
    bos.close();
    bis.close();
}

字符流

image.png
image.png
image.png

InputStreamReader 字符流-读

java.lang.Object
	java.io.Reader
		java.io.InputStreamReader

public class InputStreamReader extends Reader

//InputStreamReader是从字节流到字符流的桥接器:它使用指定的charset读取字节并将其解码为字符。
//它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。
构造器 描述
[InputStreamReader](#%3Cinit%3E(java.io.InputStream))([InputStream](InputStream.html) in) 创建一个使用默认字符集的 InputStreamReader。
[InputStreamReader](#%3Cinit%3E(java.io.InputStream,java.lang.String))([InputStream](InputStream.html) in, [String](../lang/String.html) charsetName) 创建一个使用指定 charset 的 InputStreamReader。
变量和类型 方法 描述
[String](../lang/String.html) [getEncoding](#getEncoding())() 返回此流使用的字符编码的名称。
int [read](#read())() 读一个字符。
int [read](#read(char%5B%5D,int,int))(char[] cbuf, int offset, int length) 将字符读入数组的一部分。

OutputStreamWriter 字符流-写

java.lang.Object
	java.io.Writer
		java.io.OutputStreamWriter

public class OutputStreamWriter extends Writer

//OutputStreamWriter是从字符流到字节流的桥接器:使用指定的charset将写入其中的字符编码为字节。 它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。
构造器 描述
[OutputStreamWriter](#%3Cinit%3E(java.io.OutputStream))([OutputStream](OutputStream.html) out) 创建使用默认字符编码的 OutputStreamWriter。
[OutputStreamWriter](#%3Cinit%3E(java.io.OutputStream,java.lang.String))([OutputStream](OutputStream.html) out, [String](../lang/String.html) charsetName) 创建使用指定 charset 的 OutputStreamWriter。
变量和类型 方法 描述
void [flush](#flush())() 刷新流。
[String](../lang/String.html) [getEncoding](#getEncoding())() 返回此流使用的字符编码的名称。
void [write](#write(char%5B%5D,int,int))(char[] cbuf, int off, int len) 写一个字符数组的一部分。
void [write](#write(int))(int c) 写一个字符。
void [write](#write(java.lang.String,int,int))([String](../lang/String.html) str, int off, int len) 写一个字符串的一部分。

示例:

String path = "D:\\CodeLearning\\Java开发\\Java学习笔记\\05_Java常用API\\src\\com\\xjt\\charStream\\";
//
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(path+"aaa.txt"));
//1.直接写一个字符串
osw.write("三国演义");
osw.flush();
//2.写一个字符串的一部分
String fullName = "JustinXiong";
osw.write(fullName,6,fullName.length()-6);      //写入Xiong
osw.flush();
//3.写一个字符数组
char[] chs = {'a','b','c','d','e'};
osw.write(chs);
osw.flush();
//3.写一个字符数组的一部分
osw.write(chs,0,chs.length-1);      //写入{'a','b','c','d'}
osw.flush();

osw.close();


InputStreamReader isr = new InputStreamReader(new FileInputStream(path + "aaa.txt"));
//1.一次读一个字符
//        int ch;
//        while ((ch = isr.read())!= -1){
//            System.out.print((char)ch+"-");
//        }

//2.一次读一个字符数组
int len;
char[] chars = new char[1024];
while ((len = isr.read(chars))!= -1){
    System.out.print(new String(chars,0,len));
}

isr.close();

FileWriter 字符流-写

java.lang.Object
	java.io.Writer
		java.io.OutputStreamWriter
			java.io.FileWriter
public class FileWriter extends OutputStreamWrite

//使用默认缓冲区大小将文本写入字符文件。 从字符到字节的编码使用指定的charset或平台的default charset 。
构造器 描述
[FileWriter](#%3Cinit%3E(java.io.File))([File](File.html) file) File写一个 FileWriter ,使用平台的 default charset
[FileWriter](#%3Cinit%3E(java.io.File,boolean))([File](File.html) file, boolean append) 在给出要写入的 FileWriter下构造 File ,并使用平台的 default charset 构造一个布尔值,指示是否附加写入的数据。
[FileWriter](#%3Cinit%3E(java.io.File,java.nio.charset.Charset))([File](File.html) file, [Charset](../nio/charset/Charset.html) charset) 构造一个FileWriter给予File编写和charset
[FileWriter](#%3Cinit%3E(java.io.File,java.nio.charset.Charset,boolean))([File](File.html) file, [Charset](../nio/charset/Charset.html) charset, boolean append) 构造FileWriter给出File写入, charset和一个布尔值,指示是否附加写入的数据。
[FileWriter](#%3Cinit%3E(java.lang.String))([String](../lang/String.html) fileName) 构造一个 FileWriter给出文件名,使用平台的 default charset
[FileWriter](#%3Cinit%3E(java.lang.String,boolean))([String](../lang/String.html) fileName, boolean append) 使用平台的 default charset构造一个 FileWriter给定一个文件名和一个布尔值,指示是否附加写入的数据。
[FileWriter](#%3Cinit%3E(java.lang.String,java.nio.charset.Charset))([String](../lang/String.html) fileName, [Charset](../nio/charset/Charset.html) charset) 构造一个FileWriter给出文件名和charset
[FileWriter](#%3Cinit%3E(java.lang.String,java.nio.charset.Charset,boolean))([String](../lang/String.html) fileName, [Charset](../nio/charset/Charset.html) charset, boolean append) 构造一个FileWriter给定一个文件名, charset和一个布尔值,指示是否附加写入的数据。

实际上[FileWriter](#%3Cinit%3E(java.lang.String))([String](https://www.yuque.com/yuquexiongjt/lang/String.html) fileName) 内部调用的FileOutputStream(fileName);
public FileWriter(String fileName) throws IOException {
    super(new FileOutputStream(fileName));
}
方法:
image.pngimage.png

FileReader 字符流-读

image.png
示例:

String path = "D:\\CodeLearning\\Java开发\\Java学习笔记\\05_Java常用API\\src\\com\\xjt\\charStream\\bbb.txt";

FileWriter fw = new FileWriter(path);
fw.write(11);       //  ASCII中数字对应的字符
fw.write("xiong\r\n");
fw.write("xiong",0,3);
char[] chs = {'a','b','c'};
fw.write(chs);
fw.flush();

fw.close();

//
FileReader fr = new FileReader(path);
//1.读一个字节
//        int ch;
//        while ((ch = fr.read())!= -1){
//            System.out.print((char)ch);
//        }

//2.读一个字节数组
char[] chars = new char[1024];
int len;
while ((len = fr.read(chars))!= -1){
    System.out.print(new String(chars,0,len));
}

fr.close();

BufferedReader 字符缓冲流-读

java.lang.Object
	java.io.Reader
		java.io.BufferedReader

public class BufferedReader extends Reader
//从字符输入流中读取文本,缓冲字符,以便有效地读取字符,数组和行。
可以指定缓冲区大小,或者可以使用默认大小。 对于大多数用途,默认值足够大。
构造器 描述
[BufferedReader](#%3Cinit%3E(java.io.Reader))([Reader](Reader.html) in) 创建使用默认大小的输入缓冲区的缓冲字符输入流。
[BufferedReader](#%3Cinit%3E(java.io.Reader,int))([Reader](Reader.html) in, int sz) 创建使用指定大小的输入缓冲区的缓冲字符输入流。
变量和类型 方法 描述
int [read](#read())() 读一个字符。
int [read](#read(char%5B%5D,int,int))(char[] cbuf, int off, int len) 将字符读入数组的一部分。
[String](../lang/String.html) [readLine](#readLine())() 读一行文字。

BufferedWriter 字符缓冲流-写

java.lang.Object
	java.io.Writer
		java.io.BufferedWriter

public class BufferedWriter extends Writer

//将文本写入字符输出流,缓冲字符,以便有效地写入单个字符,数组和字符串。 可以指定缓冲区大小,或者可以接受默认大小。 对于大多数用途,默认值足够大。
提供了一个newLine()方法,它使用系统自己的行分隔符概念,由系统属性line.separator定义。 并非所有平台都使用换行符('\n')来终止行。 因此,调用此方法终止每个输出行比直接编写换行符更为可取。
windows系统: \r\n
linux:  \n
Mac:  \r
构造器 描述
[BufferedWriter](#%3Cinit%3E(java.io.Writer))([Writer](Writer.html) out) 创建使用默认大小的输出缓冲区的缓冲字符输出流。
[BufferedWriter](#%3Cinit%3E(java.io.Writer,int))([Writer](Writer.html) out, int sz) 创建一个使用给定大小的输出缓冲区的新缓冲字符输出流。
变量和类型 方法 描述
void [flush](#flush())() 刷新流。
void [newLine](#newLine())() 写一个行分隔符。
void [write](#write(char%5B%5D,int,int))(char[] cbuf, int off, int len) 写一个字符数组的一部分。
void [write](#write(int))(int c) 写一个字符。
void [write](#write(java.lang.String,int,int))([String](../lang/String.html) s, int off, int len) 写一个字符串的一部分。

示例:

public static void main(String[] args) throws IOException {
    String path = "E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\bufferedChar\\";
    BufferedReader br = new BufferedReader(new FileReader(path+"aaa.txt"));
    BufferedWriter bw = new BufferedWriter(new FileWriter(path+"bbb.txt"));
    //普通方法
    //        int len;
    //        char[] bts = new char[1024];
    //        while ((len = br.read(bts)) != -1){
    //            System.out.println(new String(bts, 0, len));
    //            bw.write(bts,0,len);
    //            bw.flush();
    //        }

    //字符缓冲流特有方法 newLine()  readLine()
    String line;
    while ((line = br.readLine())!=null){
        bw.write(line);
        bw.newLine();
        bw.flush();
    }

    br.close();
    bw.close();
}

IO 流小结

字节流

image.png

字符流

image.png

文件的异常处理

  • 直接抛出到外面

image.png

  • try…catch…finally 处理异常

image.png

private static void method2(){
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        br = new BufferedReader(new FileReader("aaa.txt"));
        bw = new BufferedWriter(new FileWriter("bbb.txt"));
        String line;
        while ((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • JDK7 改进方案(推荐)

image.png
image.png

  • JDK9 改进方案

image.png
image.png

案例

获取当前项目目录:

System.out.println(System.getProperty("user.dir"));     //E:\Java_Learning\0718
System.out.println(new File("").getAbsolutePath());     //E:\Java_Learning\0718
  • 学生类存入到 ArrayList,然后将 ArrayList 写入到文件中,格式: 张三,18
String path = "E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\demos\\";
ArrayList<Student> studentArrayList = new ArrayList<>();

Student s1 = new Student("张无忌", 21);
Student s2 = new Student("张翠山", 45);
Student s3 = new Student("张三丰", 76);
studentArrayList.add(s1);
studentArrayList.add(s2);
studentArrayList.add(s3);

System.out.println(System.getProperty("user.dir"));     //E:\Java_Learning\0718
System.out.println(new File("").getAbsolutePath());     //E:\Java_Learning\0718

BufferedWriter bw = new BufferedWriter(new FileWriter(path+"aaa.txt"));
for (Student s:studentArrayList) {
    StringBuilder sb = new StringBuilder();
    sb.append(s.getName()+","+s.getAge());
    bw.write(sb.toString());
    bw.newLine();
    bw.flush();
}
bw.close();
  • 读取文件中数据,按格式封装到 GaoShou 类,并存储到集合中(排序)
//读取文件中数据,按格式封装到Person类,并存储到集合中
BufferedReader br = new BufferedReader(new FileReader(path + "bbb.txt"));
TreeSet<GaoShou> gaoShouList = new TreeSet<>(new Comparator<GaoShou>() {
    @Override
    public int compare(GaoShou gs1, GaoShou gs2) {
        //按攻击值从大到小排序,攻击值相同比较年龄(从小到大)
        int num1 = gs2.getAttack() - gs1.getAttack();
        int num2 = num1 == 0 ? gs1.getAge() - gs2.getAge() : num1;
        return num2;
    }
});

String line;
while ((line=br.readLine())!= null){
    String[] stringList = line.split(",");
    String name = stringList[0];
    Integer age = Integer.parseInt(stringList[1]);
    String menpai = stringList[2];
    String skill = stringList[3];
    Integer attack = Integer.parseInt(stringList[4]);

    GaoShou gs = new GaoShou(name, age, menpai, skill, attack);
    gaoShouList.add(gs);
}

br.close();

for (GaoShou gs:gaoShouList) {
    System.out.println(gs.getName()+","+gs.getAge()+","+gs.getMenpai()+","+gs.getSkill()+","+gs.getAttack());
}

bbb.txt
image.png
打印结果:
image.png

  • 集合到文件

image.png

  • 复制单级文件夹(文件夹中只包含文件不包含文件夹)

image.png

public static void main(String[] args) throws IOException {
    String path = "E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\bufferedChar";
    //源目录对象
    File srcFile = new File(path);
    //源目录名
    String srcDirName = srcFile.getName();
    //新目录对象
    File destDir = new File("E:\\Java_Learning\\0718\\src\\com\\xjt\\myIOStream\\demos\\"+srcDirName);
    //如果新目录不存在就创建
    if(!(destDir.exists())){
        destDir.mkdir();
    }

    //获取源目录中所有文件的 File数组
    File[] srcFiles = srcFile.listFiles();
    //获取源目录中各个文件对象并复制到新目录中
    for (File srcfile:srcFiles) {
        String fileName = srcfile.getName();
        File destfile = new File(destDir, fileName);
        //复制文件
        copyFile(srcfile,destfile);
    }
}

private static void copyFile(File srcfile,File destfile) throws IOException {
    //除了文本文件可能还有二进制文件需要使用缓冲字节流
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcfile));
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destfile));

    int len;
    byte[] bys = new byte[1024];
    while ((len = bis.read(bys))!=-1){
        bos.write(bys,0,len);
    }
    bis.close();
    bos.close();
}
  • 复制多级文件夹(文件夹中包含文件和文件夹)

image.png

public static void main(String[] args) throws IOException {
    String path = "E:\\copyFolder\\";
    //源目录对象
    File srcFile = new File(path);
    //新目录对象
    File destFile = new File("F:\\");
    copyFolders(srcFile,destFile);
}

private static void copyFolders(File srcFile, File destFile) throws IOException {
    if(srcFile.isDirectory()){
        String srcFileName = srcFile.getName();
        File newFolder = new File(destFile, srcFileName);
        if(!newFolder.exists()){
            newFolder.mkdir();
        }

        //获取源目录下所有文件集合
        File[] listSrcFiles = srcFile.listFiles();
        for (File file:listSrcFiles) {
            copyFolders(file,newFolder);
        }
    }else{
        //当srcFile是文件时,在新目录下创建该对象
        File newFile = new File(destFile, srcFile.getName());
        copyFile(srcFile,newFile);
    }
}

private static void copyFile(File srcfile,File destfile) throws IOException {
    //除了文本文件可能还有二进制文件需要使用缓冲字节流
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcfile));
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destfile));

    int len;
    byte[] bys = new byte[1024];
    while ((len = bis.read(bys))!=-1){
        bos.write(bys,0,len);
    }
    bis.close();
    bos.close();
}

标准输入输出流

System.in

public static final InputStream in

//“标准”输入流,此流已打开并准备好提供输入数据,通常该流对应于键盘输入或由主机环境或用户指定的另一输入源。

System.out

public static final PrintStream out

//“标准”输出流,此流已打开并准备接受输出数据,通常该流对应于主机环境或用户指定的显示输出或另一输出目的地。
对于简单的独立Java应用程序,编写一行输出数据的典型方法是:
     System.out.println(data)

释义:

public static void main(String[] args) throws IOException {
    InputStream in = System.in;
    InputStreamReader isr = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(isr);

    //一步完成
    //        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String line = br.readLine();

    PrintStream ps = System.out;
    ps.println(line);

    //自己实现键盘录入数据太麻烦了,java为我们提供了
    Scanner sc = new Scanner(System.in);
    /*
        public Scanner(InputStream source) {
            this(new InputStreamReader(source), WHITESPACE_PATTERN);
        }
        * */
}

字节打印流

image.png
image.png
image.png

对象序列化反序列化流

image.png

  • ObjectOutputStream
public class ObjectOutputStream
extends OutputStream
implements ObjectOutput, ObjectStreamConstantsObjectOutputStream

//将Java对象的原始数据类型和图形写入OutputStream。可以使用ObjectInputStream读取(重构)对象,可以通过使用流的文件来完成对象的持久存储。 如果流是网络套接字流,则可以在另一个主机或另一个进程中重新构建对象。只有实现java.io.Serializable接口的对象才能写入流。

//构造方法
ObjectOutputStream(OutputStream out) 	//创建一个写入指定OutputStream的ObjectOutputStream

//方法
public final void writeObject(Object obj) throws IOException	//将指定的对象写入ObjectOutputStream

image.png
image.png
image.png
序列化 Student 类,存储到文件中,再从文件中读取反序列化,如果修改了 Student 类会造成

Exception in thread “main” java.io.InvalidClassException: com.xjt.myIOStream.serializableStream.Student; local class incompatible: stream classdesc serialVersionUID = 3001235629277929748, local class serialVersionUID = 5223036644798306068

详情可查看 JDK-Serializable
image.png
image.png

Properties 字典流

java.lang.Object
	java.util.Dictionary<K,V>
		java.util.Hashtable<Object,Object>
			java.util.Properties

public class Properties extends Hashtable<Object,Object>

//构造方法
Properties() 	//创建一个没有默认值的空属性列表

image.png

Properties pp = new Properties();
pp.setProperty("name","张无忌");
pp.setProperty("age","21");
pp.setProperty("skill","九阳神功");

System.out.println("pp.getProperty(\"name\")="+pp.getProperty("name"));

Set<String> stringSet = pp.stringPropertyNames();
for (String item: stringSet) {
    String value = pp.getProperty(item);
    System.out.println(value);
}

Properties 和 IO 流结合

image.png
案例:猜数字游戏
image.png
游戏类:
image.png
main()
image.png


文章作者: CoderXiong
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 CoderXiong !
  目录