Java输入输出tutorial

LearningJava fileoperation and IO流, implementationdata 读取 and 写入

返回tutoriallist

Java输入输出tutorial

Java输入输出(Input/Output) is Javaprogrammingin非常 important 一部分, 它用于processing程序 and out 部设备 (such asfile, 键盘, 屏幕etc.) 之间 data交换. Javaproviding了丰富 IOclass and interface, 用于implementation各种输入输出operation. 本tutorial将介绍Java IO体系structure, 常用 IOclass and interface, 以及such as何using它们来forfileoperation and dataprocessing.

1. IO体系overview

1.1 IO流 concepts

in Javain, IOoperation is through流(Stream)来implementation . 流 is aabstractionconcepts, 它代表data 流动. 流 一端 is datasources, 另一端 is data目 地. 根据data 流向, 流可以分 for :

  • 输入流(Input Stream): from datasources读取data to 程序in.
  • 输出流(Output Stream): from 程序写入data to data目 地.

1.2 IO流 classification

Java IO流可以按照不同 方式classification:

1.2.1 按dataclass型classification
  • 字节流: 以字节 for 单位processingdata, 适用于processing二进制data, such asgraph片, 音频, 视频etc..
  • 字符流: 以字符 for 单位processingdata, 适用于processing文本data, such as文本file, configurationfileetc..
1.2.2 按流 functionsclassification
  • node流: 直接 and datasources or data目 地相连 流, such asFileInputStream, FileOutputStreametc..
  • processing流: package装 in node流之 on , 用于providing额 out functions, such as缓冲, 转换etc., such asBufferedInputStream, BufferedOutputStreametc..

1.3 IO流 层次structure

Java IO流体系structure非常庞 big , 主要including以 under 几个coreclass and interface:

1.3.1 字节流
  • InputStream: 字节输入流 abstraction基class.
  • OutputStream: 字节输出流 abstraction基class.
1.3.2 字符流
  • Reader: 字符输入流 abstraction基class.
  • Writer: 字符输出流 abstraction基class.

2. 字节流

2.1 输入字节流

2.1.1 FileInputStream

FileInputStream is a node流, 用于 from filein读取字节data.

// usingFileInputStream读取file
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            // creationFileInputStreamobject
            fis = new FileInputStream("example.txt");
            
            // 读取file in 容
            int byteData;
            while ((byteData = fis.read()) != -1) {
                System.out.print((char) byteData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
2.1.2 BufferedInputStream

BufferedInputStream is a processing流, 它package装了一个字节输入流, providing缓冲functions, improving读取efficiency.

// usingBufferedInputStream读取file
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class BufferedInputStreamDemo {
    public static void main(String[] args) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            // creationFileInputStreamobject
            fis = new FileInputStream("example.txt");
            // creationBufferedInputStreamobject, package装FileInputStream
            bis = new BufferedInputStream(fis);
            
            // 读取file in 容
            int byteData;
            while ((byteData = bis.read()) != -1) {
                System.out.print((char) byteData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (bis != null) {
                try {
                    bis.close(); // 关闭BufferedInputStream会自动关闭package装 FileInputStream
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2.2 输出字节流

2.2.1 FileOutputStream

FileOutputStream is a node流, 用于向filein写入字节data.

// usingFileOutputStream写入file
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            // creationFileOutputStreamobject
            // 第二个parameter for true表示追加写入, false表示覆盖写入
            fos = new FileOutputStream("output.txt", true);
            
            // 写入data
            String content = "Hello, Java IO!\n";
            byte[] byteArray = content.getBytes();
            fos.write(byteArray);
            
            System.out.println("data写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
2.2.2 BufferedOutputStream

BufferedOutputStream is a processing流, 它package装了一个字节输出流, providing缓冲functions, improving写入efficiency.

// usingBufferedOutputStream写入file
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedOutputStreamDemo {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            // creationFileOutputStreamobject
            fos = new FileOutputStream("output.txt", true);
            // creationBufferedOutputStreamobject, package装FileOutputStream
            bos = new BufferedOutputStream(fos);
            
            // 写入data
            String content = "Hello, BufferedOutputStream!\n";
            byte[] byteArray = content.getBytes();
            bos.write(byteArray);
            
            // 刷 new 缓冲区, 确保data写入file
            bos.flush();
            
            System.out.println("data写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (bos != null) {
                try {
                    bos.close(); // 关闭BufferedOutputStream会自动关闭package装 FileOutputStream
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3. 字符流

3.1 输入字符流

3.1.1 FileReader

FileReader is a node流, 用于 from filein读取字符data.

// usingFileReader读取file
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
    public static void main(String[] args) {
        FileReader fr = null;
        try {
            // creationFileReaderobject
            fr = new FileReader("example.txt");
            
            // 读取file in 容
            int charData;
            while ((charData = fr.read()) != -1) {
                System.out.print((char) charData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
3.1.2 BufferedReader

BufferedReader is a processing流, 它package装了一个字符输入流, providing缓冲functions and 按行读取functions, improving读取efficiency.

// usingBufferedReader读取file
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderDemo {
    public static void main(String[] args) {
        FileReader fr = null;
        BufferedReader br = null;
        try {
            // creationFileReaderobject
            fr = new FileReader("example.txt");
            // creationBufferedReaderobject, package装FileReader
            br = new BufferedReader(fr);
            
            // 按行读取file in 容
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (br != null) {
                try {
                    br.close(); // 关闭BufferedReader会自动关闭package装 FileReader
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3.2 输出字符流

3.2.1 FileWriter

FileWriter is a node流, 用于向filein写入字符data.

// usingFileWriter写入file
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterDemo {
    public static void main(String[] args) {
        FileWriter fw = null;
        try {
            // creationFileWriterobject
            // 第二个parameter for true表示追加写入, false表示覆盖写入
            fw = new FileWriter("output.txt", true);
            
            // 写入data
            String content = "Hello, Java FileWriter!\n";
            fw.write(content);
            
            System.out.println("data写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
3.2.2 BufferedWriter

BufferedWriter is a processing流, 它package装了一个字符输出流, providing缓冲functions and 换行functions, improving写入efficiency.

// usingBufferedWriter写入file
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterDemo {
    public static void main(String[] args) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            // creationFileWriterobject
            fw = new FileWriter("output.txt", true);
            // creationBufferedWriterobject, package装FileWriter
            bw = new BufferedWriter(fw);
            
            // 写入data
            bw.write("Hello, BufferedWriter!");
            bw.newLine(); // 写入换行符
            bw.write("This is a new line.");
            
            // 刷 new 缓冲区, 确保data写入file
            bw.flush();
            
            System.out.println("data写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (bw != null) {
                try {
                    bw.close(); // 关闭BufferedWriter会自动关闭package装 FileWriter
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

4. 转换流

4.1 InputStreamReader

InputStreamReader is a 转换流, 它将字节输入流转换 for 字符输入流.

// usingInputStreamReader读取file
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputStreamReaderDemo {
    public static void main(String[] args) {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        try {
            // creationFileInputStreamobject
            fis = new FileInputStream("example.txt");
            // creationInputStreamReaderobject, 将字节流转换 for 字符流
            // 可以指定字符编码, such asUTF-8
            isr = new InputStreamReader(fis, "UTF-8");
            
            // 读取file in 容
            int charData;
            while ((charData = isr.read()) != -1) {
                System.out.print((char) charData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (isr != null) {
                try {
                    isr.close(); // 关闭InputStreamReader会自动关闭package装 FileInputStream
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

4.2 OutputStreamWriter

OutputStreamWriter is a 转换流, 它将字符输出流转换 for 字节输出流.

// usingOutputStreamWriter写入file
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class OutputStreamWriterDemo {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            // creationFileOutputStreamobject
            fos = new FileOutputStream("output.txt", true);
            // creationOutputStreamWriterobject, 将字符流转换 for 字节流
            // 可以指定字符编码, such asUTF-8
            osw = new OutputStreamWriter(fos, "UTF-8");
            
            // 写入data
            osw.write("Hello, OutputStreamWriter!");
            osw.write("\n");
            osw.write("This is a test.");
            
            // 刷 new 缓冲区, 确保data写入file
            osw.flush();
            
            System.out.println("data写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (osw != null) {
                try {
                    osw.close(); // 关闭OutputStreamWriter会自动关闭package装 FileOutputStream
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

5. 标准输入输出流

5.1 标准输入流

标准输入流(System.in) is a InputStreamobject, 用于 from 键盘读取data.

// using标准输入流读取键盘输入
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StandardInputDemo {
    public static void main(String[] args) {
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            // creationInputStreamReaderobject, package装System.in
            isr = new InputStreamReader(System.in);
            // creationBufferedReaderobject, package装InputStreamReader
            br = new BufferedReader(isr);
            
            System.out.print("请输入您 姓名: ");
            String name = br.readLine();
            
            System.out.print("请输入您 年龄: ");
            String ageStr = br.readLine();
            int age = Integer.parseInt(ageStr);
            
            System.out.println("您 good , " + name + "!您今年" + age + "岁. ");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

5.2 标准输出流

标准输出流(System.out) is a PrintStreamobject, 用于向屏幕输出data.

// using标准输出流输出data
public class StandardOutputDemo {
    public static void main(String[] args) {
        // usingSystem.out输出data
        System.out.println("Hello, World!");
        
        // usingSystem.out.print输出data, 不自动换行
        System.out.print("请输入您 姓名: ");
        
        // usingSystem.out.printfformat输出data
        String name = "张三";
        int age = 18;
        double score = 95.5;
        System.out.printf("姓名: %s, 年龄: %d, 成绩: %.2f\n", name, age, score);
    }
}

6. fileoperation

6.1 Fileclass

Fileclass用于表示file or Table of Contents path, 它providing了一系列method用于operationfile and Table of Contents, such ascreation, delete, renameetc..

// Fileclass using
import java.io.File;
import java.io.IOException;

public class FileDemo {
    public static void main(String[] args) {
        // creationFileobject
        File file = new File("test.txt");
        
        try {
            // creationfile
            if (file.createNewFile()) {
                System.out.println("filecreation成功!");
            } else {
                System.out.println("file已存 in !");
            }
            
            // 获取fileinformation
            System.out.println("file名称: " + file.getName());
            System.out.println("filepath: " + file.getPath());
            System.out.println("绝 for path: " + file.getAbsolutePath());
            System.out.println(" is 否存 in : " + file.exists());
            System.out.println(" is 否 is file: " + file.isFile());
            System.out.println(" is 否 is Table of Contents: " + file.isDirectory());
            System.out.println("file big  small : " + file.length() + "字节");
            System.out.println("最 after modify时间: " + file.lastModified());
            
            // renamefile
            File newFile = new File("new_test.txt");
            if (file.renameTo(newFile)) {
                System.out.println("filerename成功!");
            } else {
                System.out.println("filerename失败!");
            }
            
            // deletefile
            if (newFile.delete()) {
                System.out.println("filedelete成功!");
            } else {
                System.out.println("filedelete失败!");
            }
            
            // creationTable of Contents
            File directory = new File("test_dir");
            if (directory.mkdir()) {
                System.out.println("Table of Contentscreation成功!");
            } else {
                System.out.println("Table of Contentscreation失败!");
            }
            
            // 列出Table of Contentsin file and 子Table of Contents
            File[] files = directory.listFiles();
            if (files != null) {
                System.out.println("Table of Contentsin file and 子Table of Contents: ");
                for (File f : files) {
                    System.out.println(f.getName());
                }
            }
            
            // deleteTable of Contents
            if (directory.delete()) {
                System.out.println("Table of Contentsdelete成功!");
            } else {
                System.out.println("Table of Contentsdelete失败!");
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.2 filefilter器

Fileclassproviding了listFiles(FileFilter filter)method, 用于filterTable of Contentsin file.

// filefilter器 using
import java.io.File;
import java.io.FilenameFilter;

public class FileFilterDemo {
    public static void main(String[] args) {
        // creationFileobject
        File directory = new File(".");
        
        // usingFilenameFilterfilter.txtfile
        File[] txtFiles = directory.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");
            }
        });
        
        // 显示filter after  file
        System.out.println("Table of Contentsin .txtfile: ");
        if (txtFiles != null) {
            for (File file : txtFiles) {
                System.out.println(file.getName());
            }
        }
        
        // usinglambda表达式filter.javafile
        File[] javaFiles = directory.listFiles((dir, name) -> name.endsWith(".java"));
        
        // 显示filter after  file
        System.out.println("\nTable of Contentsin .javafile: ");
        if (javaFiles != null) {
            for (File file : javaFiles) {
                System.out.println(file.getName());
            }
        }
    }
}

7. 序列化 and 反序列化

7.1 what is 序列化 and 反序列化?

序列化 is 指将object转换 for 字节序列 过程, 反序列化 is 指将字节序列转换 for object 过程. 序列化 and 反序列化主要用于object store and network传输.

7.2 implementation序列化 and 反序列化

要implementationobject 序列化, 需要让classimplementationSerializableinterface. Serializableinterface is a 标记interface, 它没 has 任何method, 只 is 用于标记该class可以被序列化.

// 序列化 and 反序列化example
import java.io.*;

// implementationSerializableinterface
class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class SerializationDemo {
    public static void main(String[] args) {
        // 序列化object
        serializeObject();
        
        // 反序列化object
        deserializeObject();
    }
    
    // 序列化object
    public static void serializeObject() {
        Person person = new Person("张三", 18);
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            // creationFileOutputStreamobject
            fos = new FileOutputStream("person.ser");
            // creationObjectOutputStreamobject, package装FileOutputStream
            oos = new ObjectOutputStream(fos);
            
            // 序列化object
            oos.writeObject(person);
            
            System.out.println("object序列化成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    // 反序列化object
    public static void deserializeObject() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            // creationFileInputStreamobject
            fis = new FileInputStream("person.ser");
            // creationObjectInputStreamobject, package装FileInputStream
            ois = new ObjectInputStream(fis);
            
            // 反序列化object
            Person person = (Person) ois.readObject();
            
            System.out.println("object反序列化成功!");
            System.out.println("反序列化 object: " + person);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

8. NIOIntroduction

8.1 what is NIO?

NIO(New IO) is Java 1.4引入 一组 new IO API, 它providing了更 high 效 IOoperation方式. NIO and 传统 IO相比, 具 has 以 under 特点:

  • 非阻塞IO: NIOsupport非阻塞IOoperation, 一个thread可以processing many 个IOoperation.
  • 缓冲区(Buffer): NIOusing缓冲区来storedata, improving了dataprocessingefficiency.
  • 通道(Channel): NIOusing通道来传输data, 通道可以双向传输data.
  • 选择器(Selector): NIOusing选择器来monitor many 个通道 event, improving了system concurrentprocessingcapacity.

8.2 NIO basicusing

// NIObasicusingexample
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NIODemo {
    public static void main(String[] args) {
        // usingNIO写入file
        writeFileWithNIO();
        
        // usingNIO读取file
        readFileWithNIO();
    }
    
    // usingNIO写入file
    public static void writeFileWithNIO() {
        Path path = Paths.get("nio_output.txt");
        FileChannel channel = null;
        ByteBuffer buffer = null;
        
        try {
            // 打开通道
            channel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
            
            // creation缓冲区
            String content = "Hello, NIO!\n";
            buffer = ByteBuffer.allocate(content.length());
            buffer.put(content.getBytes());
            buffer.flip(); // 切换 to 读模式
            
            // 写入data
            channel.write(buffer);
            
            System.out.println("NIO写入file成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭通道
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    // usingNIO读取file
    public static void readFileWithNIO() {
        Path path = Paths.get("nio_output.txt");
        FileChannel channel = null;
        ByteBuffer buffer = null;
        
        try {
            // 打开通道
            channel = FileChannel.open(path, StandardOpenOption.READ);
            
            // creation缓冲区
            buffer = ByteBuffer.allocate(1024);
            
            // 读取data
            int bytesRead;
            while ((bytesRead = channel.read(buffer)) != -1) {
                buffer.flip(); // 切换 to 读模式
                
                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get());
                }
                
                buffer.clear(); // 清空缓冲区, 切换 to 写模式
            }
            
            System.out.println("\nNIO读取file成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭通道
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

实践case: filecopytool

现 in , 让我们creation一个filecopytool, usingJava IO来implementationfile copyfunctions.

// filecopytool
import java.io.*;

public class FileCopyTool {
    public static void main(String[] args) {
        String sourceFile = "source.txt";
        String destFile = "dest.txt";
        
        // creationsourcesfile并写入data
        createSourceFile(sourceFile);
        
        // copyfile
        boolean success = copyFile(sourceFile, destFile);
        
        if (success) {
            System.out.println("filecopy成功!");
            // verificationcopy结果
            verifyCopyResult(destFile);
        } else {
            System.out.println("filecopy失败!");
        }
    }
    
    // creationsourcesfile并写入data
    private static void createSourceFile(String sourceFile) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        
        try {
            fw = new FileWriter(sourceFile);
            bw = new BufferedWriter(fw);
            
            bw.write("Hello, File Copy Tool!");
            bw.newLine();
            bw.write("This is a test file.");
            bw.newLine();
            bw.write("It contains some test data for file copying.");
            
            bw.flush();
            System.out.println("sourcesfilecreation成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    // copyfile
    private static boolean copyFile(String sourceFile, String destFile) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        
        try {
            // creation输入流
            fis = new FileInputStream(sourceFile);
            bis = new BufferedInputStream(fis);
            
            // creation输出流
            fos = new FileOutputStream(destFile);
            bos = new BufferedOutputStream(fos);
            
            // 读取并写入data
            byte[] buffer = new byte[1024];
            int bytesRead;
            
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            
            bos.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            // 关闭流
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    // verificationcopy结果
    private static void verifyCopyResult(String destFile) {
        FileReader fr = null;
        BufferedReader br = null;
        
        try {
            fr = new FileReader(destFile);
            br = new BufferedReader(fr);
            
            System.out.println("\ncopy after  file in 容: ");
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

这个filecopytoolimplementation了以 under functions:

  1. creationsourcesfile并写入testdata
  2. using缓冲流copyfile
  3. verificationcopy结果, 显示copy after file in 容

互动练习

练习1: file读写operation

writing一个Java程序, from 键盘读取user输入 文本, 将其写入 to 一个filein, 然 after 再 from 该filein读取data并显示 in 屏幕 on .

练习2: file in 容statistics

writing一个Java程序, statistics一个文本filein 行数, 单词数 and 字符数.

练习3: object序列化 and 反序列化

creation一个Studentclass, package含学号, 姓名 and 成绩property, implementationSerializableinterface. writing一个Java程序, 将Studentobject序列化 to filein, 然 after 再 from filein反序列化并显示objectinformation.