IO流

本文详细介绍了Java中的IO流概念,包括字节流和字符流的基本使用方法,以及各种过滤流的功能和应用场景。此外,还涉及了文件操作和对象序列化的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、IO
1. 概念:流是内存和其他存储设备中传输数据的通道、管道。
2. 分类
① 按方向分:(以JVM为参照物)【重点】
输入流:将<存储设备>中的数据,读入到<内存>中。
输出流:将<内存>中的数据,写入到<存储设备>中。
② 按单位分:
字节流:以字节为单位,可以操作所有类型的文件。
字符流:以字符为单位,只能操作文本文件。
                      (可以用记事本打开的文件,例如:.java/.txt/.c/.html)
    ③ 按功能分:
节点流:具有基本的读写功能。
过滤流:在节点流的基础上,增强新的功能。

二、字节流
1. 字节流的父类(抽象类)
① InputStream:字节输入流---》读操作:read
② OutputStream:字节输出流---》写操作:write

2. 字节节点流【重点】
① FileOutputStream:文件字节输出流
   常用的构造方法:
a. FileOutputStream fos = new FileOutputStream("E:/CoreJava/test/a.txt");
   I. 参数:指定文件的路径,E:/CoreJava/test/a.txt 
                       或是 E:\\CoreJava\\test\\a.txt
   II. 如果指定的文件不存在,系统默认新创建一个文件。
       但是如果指定的文件夹不存在,则系统报错,错误信息:
   java.io.FileNotFoundException (系统找不到指定的路径。)
           III. 绝对路径:盘符:/文件夹名/文件名
b. FileOutputStream fos = new FileOutputStream("a.txt"); 
               I.参数:指定文件的路径,默认在当前项目的根目录下查找文件,没有则创建
   II. 相对路径:默认在当前项目的根目录下查找文件
c. FileOutputStream fos = new FileOutputStream("file/a.txt");【开发应用】
d. FileOutputStream fos = new FileOutputStream("file/a.txt",true);
   I. 第二个参数:类型是 boolean
                               true-在原有内容上追加(不覆盖原有内容)
                               false-覆盖原有的内容 (默认)    
   
    常用的方法:
a. public void write(int b):将单个字节的内容写入到文件中。
                b. public void write(byte[] bs):一次性将多个字节写入到文件中。
c. public void write(byte[] bs,int off,int len):一次性将多个字节写入到文件中,

                  将bs数组中一部分内容写入文件中,起始下标off,写入长度len

eg:

package demo20171115;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class Qustion_13_8 {
public static void main(String[] args) throws InterruptedException,
IOException {
FileOutputStream fileOutputStream = new FileOutputStream("test.txt");
String str = "Hello World";
byte[] b = str.getBytes();
fileOutputStream.write(b); // 将多个字节存到文件中
}
}

    ② FileInputStream:文件字节输入流
   常用的构造方法:
a. FileInputStream fis = new FileInputStream("f.txt");
   I. 参数:代表文件的路径,如果指定文件不存在,系统不会自动创建,
             运行报错,错误信息:
java.io.FileNotFoundException(系统找不到指定的文件。)

   常用的方法:
a. public int read():一次性读取一个字节的内容,返回值代表读取的内容,
                      如果达到文件的尾部,则返回-1.
  
将文件中内容一次性读取?
while(true){
int r = fis.read();
if(r==-1){
break;
}
System.out.println((char)r);
}
b. public int read(byte[] bs):一次性读取多个字节的内容,将读取的字节内容自动存储到bs数组中,
                              返回值代表实际读取的字节个数。
c. public int read(byte[] bs,int off,int len):一次性读取多个字节的内容,
                              将读取的字节内容存储到数组bs中(存储的起始下标off,读取的个数len),
  返回值代表实际读取的字节个数

思考:如何实现文件的拷贝???  
while(true){
int r = fis.read();
if(r==-1) break;
fos.write(r);

}

eg:

package demo20171116;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.stream.FileImageInputStream;
/*
 * 文件拷贝练习
 */
public class Question_13 {
public static void main(String[] args) throws IOException {
//创建节点输入流
FileInputStream fileInputStream = new FileInputStream("file/copy.txt");
//增强节点流,包装过滤流
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
//创建节点输出流
FileOutputStream fileOutputStream = new FileOutputStream("paste.txt");
//增强节点流,包装过滤流
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
while(true){
int read = bufferedInputStream.read();
if(read==-1){                                    //达到文件底部结束循环
break;
}
bufferedOutputStream.write(read);
}
//关闭流
bufferedInputStream.close();
bufferedOutputStream.close();
}
}

3. 过滤流
① BufferedInputStream/BufferedOutputStream
a. 缓冲流,提高IO读写效率,减少访问磁盘的次数。
b. 数据存储在缓冲中,利用flush方法将缓冲区的数据清空,(写入到文件中);

    或是直接利用close方法清空缓冲区。

eg:文件拷贝

② DataOutputStream/DataInputStream
a. 操作8种基本数据类型
   readByte()/readShort()/readInt()/readLong()/readFloat()/readDouble()...
   writeByte(形参)/writeShort(形参)....

    b. 可以操作字符串:readUTF() / writeUTF(参数)

eg:数据输入流

package test_io;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class TestDataInputStream {
public static void main(String[] args) throws IOException {

FileInputStream fis = new FileInputStream("file/d.txt");
DataInputStream dis = new DataInputStream(fis);

double d = dis.readDouble();
System.out.println("d="+d);

dis.close();
}
}

eg:数据输出流

package test_io;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestDataOutputStream {
public static void main(String[] args) throws IOException {
//将一个double类型的:12.3写入到文件中
//1. 创建节点流对象
FileOutputStream fis = new FileOutputStream("file/d.txt");
//2. 包装过滤流
DataOutputStream dos = new DataOutputStream(fis);
//3. 写操作
double d=12.3;
dos.writeDouble(d);
//4.关闭流:关闭最外层
dos.close();
}
}

③ ObjectOutputStream/ObjectInputStream
a. 具有缓冲作用
b. 可以操作8种基本数据类型/String
c. 可以操作对象
writeObject(Object o):将对象写入到文件中
readObject():从文件中读取一个对象的内容,返回值类型是Object.

对象序列化:
   概念:将对象放在流上进行传输的过程称为对象序列化。【重点】
   要求:参与对象序列化的对象是可序列化的,可序列化的要求是
     对象的类实现java.io.Serializable接口。【重点】
 
   注意:① 被transient修饰的属性不参与对象序列化。
         ② 达到文件尾部的标志:java.io.EOFException
③ 如果参与对象序列化的对象中的属性是自定义类型,
    则该对象也必须是可序列化的。
④ 如果对集合进行对象序列化,则必须保证集合中所有的元素

    都是可序列化的。

eg:

package test_io;
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private transient int age;//不参与对象序列化
private double score;
private Address addr=new Address();
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age, double score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
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;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "name=" + name + ", age=" + age + ", score=" + score;
}
}
class Address  implements Serializable{
}

eg;

对象输入流

package test_io;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class TestObjectInputStream {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("file/stu.txt");                                      
ObjectInputStream ois = new ObjectInputStream(fis);

Object o=ois.readObject();
System.out.println(o);
/* Object o2=ois.readObject();
System.out.println(o2);*/
ois.close();
}
}

eg:对象输出流

package test_io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class TestObjectOutputStream {
public static void main(String[] args) throws IOException {
//将一个对象写入到文件中

//1. 创建节点流对象
FileOutputStream fis = new FileOutputStream("file/stu.txt");
//2. 包装过滤流
ObjectOutputStream oos = new ObjectOutputStream(fis);                          //读出的文件看不懂

Student s1 = new Student("ww",38,100.0);                        
//3. 写操作
oos.writeObject(s1);
//4. 关闭流:外层
oos.close();
}
}

三、字符流
1. 常用编码:
① ISO8859-1 :西欧 ,底端存储占用1B
② GBK  简体中文
   GB2312
   GB18030
⑤ BIG5 台湾-繁体中文
⑥ UTF-8  万国码,底端采用动态编码,中文占 2 ~ 3个字节,英文符号:1B
       如果编码方式和解码方式不一致,会导致乱码。
2. 字符流的父类(抽象类)
① Writer:字符输出流---》写操作
② Reader:字符输入流---》读操作
3. 节点流
    ① FileWriter:文件字符输出流
   a. public void write(int b):将单个字符写入文件中
   b. public void write(String str):将多个字符一次性写入到文件中

   c. public void write(char[] c):将多个字符一次性写入到文件中

eg:

package test_basic;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileWriter {
public static void main(String[] args) throws IOException {
//1. 创建文件字符输出流对象
FileWriter fw = new FileWriter("file/b.txt");
//2. 写操作
// fw.write('中');
/*String str="爱你,中国!";
fw.write(str);*/
String str="你好,hi";
char[] cs = str.toCharArray();
fw.write(cs);
//3. 关闭流
fw.close();
}
}

② FileReader:文件字符输入流
   a. public int read():一次读取一个字符的内容,达到文件的尾部,返回—1.
   b. public int read(char[] c):一次性读取多个字符的内容,并且将读取的字符内容存储到
                                 数组中,返回值代表实际读取的字符个数,达到文件尾部,
    则返回-1.
   c. public int read(char[] c,int off,int len):一次性读取多个字符的内容,将读取的内容
                                 存储到字符数组中,存储下标为off,读取的字符个数为len,达到文件

尾部,返回-1.

eg:

package test_basic;
import java.io.FileReader;
import java.io.IOException;
public class TestFileReader {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("file/b.txt");
/*int r = fr.read();
System.out.println((char)r);*/
/*while(true){
int r = fr.read();
if(r==-1) break;
System.out.println((char)r);
}*/
char[] c=new char[3];
int count = fr.read(c);
System.out.println("字符的个数:"+count);
for(int i=0;i<c.length;i++){
System.out.println(c[i]);
}

fr.close();
}
}

4. 过滤流
① BufferedReader:
    操作:public String readLine():一次性读取一个文本行的内容。

                                达到文件的尾部,返回null.

eg:

package test_basic;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestInputStreamReader {
public static void main(String[] args)  {
BufferedReader br=null;
try {
//1. 创建节点流(字节流)
FileInputStream fis = new FileInputStream("file/b.txt");
//2. 创建桥转换流:将字节流---》字符流,同时设置编解码方式
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
//3. 包装过滤流:目的:增强读功能
br = new BufferedReader(isr);
//4. 读操作
while(true){
String r = br.readLine();
if(r==null) break;
System.out.println(r);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//5. 关闭流:最外层流
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

② PrintWriter:

a. 可以操作8种基本数据类型
b. 可以将String写入到文件中
   print(参数):将内容写入到文件中不换行
   println(参数):将内容写入到文件中,自动换行。
c. 可以将对象的内容写入到文件中:

println(Object o)/print(Object o)

eg:

package test_basic;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class TestOutputStreamWriter {
public static void main(String[] args)  {
//UTF-8
PrintWriter pw=null;
try{
//1. 创建节点流(字节)
FileOutputStream fos = new FileOutputStream("file/f.txt");
//2. 桥转换:字节流--》字符流,同时设置编解码格式
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
//3. 包转过滤流
pw = new PrintWriter(osw);
//4. 写操作
pw.println("白日依山尽,");
pw.println("娟姐最美。");
pw.print("呵呵呵达...");
}catch(Exception e){
e.printStackTrace();
}finally{
//5. 关闭流
if(pw!=null){
pw.close();
}
}
}
}

四、File类
1. File是对文件本身操作,例如:删除文件、改名字等。
   IO流是对文件的内容进行操作,读或是写操作。
2. 常用方法:
① File(String pathName):执行操作的文件、文件夹的路径
        ② String getName():获取文件/文件名字,文件包含扩展名

③ String getAbsolutePath():获取文件、文件夹的绝对路径

eg:

package test_io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestFile {
public static void main(String[] args) throws IOException {
File f = new File("file");
/*boolean n = f.createNewFile();//新创建一个文件,成功——true;否则-false
System.out.println(n);*/
/*boolean n = f.mkdir();//创建文件夹
System.out.println(n);*/
/*boolean d = f.delete();
System.out.println(d);*/
/*File f2 = new File("file/d_copy.txt");
f.renameTo(f2);*/
// f.setReadOnly();
// System.out.println(f.getName());
/*System.out.println(f.exists());
System.out.println(f.getAbsolutePath());*/
File[] fs=f.listFiles();
System.out.println("个数:"+fs.length);
//获取file文件夹中所有的文件名
for(File file:fs){
if(file.isFile()){
System.out.println(file.getName());
}
}
// System.out.println(f.isFile());
System.out.println(f.isDirectory());
File f1 = new File("file/y.txt");
FileOutputStream fos = new FileOutputStream(f1);
fos.write(65);
fos.close();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值