文件、IO流、字符流、字节流、字节流和字符流的转换、打印流、序列化流(对象流)

1、文件

  • 文件构造器

    public static void main(String[] args) {
    		
    		File file = new File("D:\\Java课程\\教案\\09-java基础语法\\09.txt");
        
    		System.out.println(file.getName());
    		System.out.println(file.exists());
    		System.out.println(file.getParent());
    		System.out.println(file.isDirectory());
    		System.out.println(file.isFile());
    		
    		System.out.println("***************************");
    		File file1 = new File("D:\\Java课程\\教案\\09-java基础语法");
    		System.out.println(file1.getName());
    		System.out.println(file1.exists());
    		System.out.println(file1.getParent());
    		System.out.println(file1.isDirectory());
    		System.out.println(file1.isFile());
    }
    
  • 创建文件

    public static void main(String[] args) {
    
        File file = new File("D:\\Java课程\\教案\\09-java基础语法\\10.txt");
    
        // 判断本地硬盘中是否在已经存在要创建的文件
        if(!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace(); // 当系统路径不存在时抛异常
            }
        }
    
    }
    
  • 创建目录

    public static void main(String[] args) {
    		
        File file = new File("D:\\Java课程\\教案\\09-java基础语法\\test");
    
        if(!file.exists()) {
            file.mkdir(); // 创建单级目录
        }
    
        File file1 = new File("D:\\Java课程\\教案\\09-java基础语法\\test1\\test2");
    
        if(!file1.exists()) {
            boolean sign = file1.mkdirs(); // 创建多级目录
            System.out.println(sign);
        }
    
    }
    
  • 删除文件

    public static void main(String[] args) {
    		
        File file = new File("D:\\Java课程\\教案\\09-java基础语法\\09.txt");
    
        if(file.exists()) {			
            file.delete();
        }
    
    }
    
  • 文件重命名

    public static void main(String[] args) {
    
        File file = new File("D:\\Java课程\\教案\\09-java基础语法\\10.txt");
        File file1 = new File("D:\\Java课程\\教案\\09-java基础语法\\11.txt");
    
        if(file.exists()) {			
            file.renameTo(file1);
        }
    
    }
    
  • 文件获取

    public static void main(String[] args) {
    
        File file = new File("D:\\Java课程\\教案\\09-java基础语法");
    
        String[] strArr = file.list();
    
        for(String str:strArr) {
            System.out.println(str);
        }
    
        File[] fileArr = file.listFiles();
        for(File f:fileArr) {
            System.out.println(f.getName());
        }
    }
    

练习:递归获取某个目录下所有的文件名

2、IO流

  • 流的介绍

    IO(input/output):输入和输出,指的是某个设备或者环境进行数据的输入或者输出。例如:键盘的输入,显示器的输出

    java将输入和输出的问题抽象成流对象解决

    在java.io包中操作文件内容主要有两大类:字节流、字符流,两类都分为输入和输出操作

    字符流处理的单元为2个字节的Unicode字符,分操作字符、字符数组或字符串,而字节流处理单元为1个字节,操作字节和字节数组。如果是音频文件、图片、歌曲、就用字节流好点,如果关系到中文的,用字符流好点。字节流可用于任何类型的对象,包括二进制对象,而字符流只能处理字符或者字符串,字节流提供了处理任何类型的IO操作的功能,但它不能直接处理Unicode字符,而字符流可以。

3、字符流

  • 字符输出流的超类

    Writer:子类FileWriter,BufferedWriter

    如果是输出流则以Write结尾

    close():需要手动关闭的资源,一般都是虚拟机之外的资源,比如说端口、文件、显存。这些都是虚拟机不能通过垃圾回收机制来释放的。所以我们要手动的调用close()方法来释放。

    public static void main(String[] args) {
    
        FileWriter fileWriter = null;
    
        try {
            fileWriter = new FileWriter(new File("D:\\Java课程\\教案\\09-java基础语法\\11.txt"));
            fileWriter.write("你好111");
            //			fileWriter.flush();
            //			fileWriter.close();
    
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    
    }
    
  • 字符输入流的超类

    Reader: 子类FileReader,BufferedReader

    如果是输入流则以Reader结尾

    fileReader = new FileReader("D:\\Java课程\\教案\\09-java基础语法\\11.txt");
    
    //			int a = fileReader.read();
    //			System.out.println((char)a);
    //			int b = fileReader.read();
    //			System.out.println((char)b);
    
    // read()返回-1,说明已经读取完成
    int i = -1;
    while((i = fileReader.read()) != -1) {
        System.out.println((char)i);
    }
    
    public static void main(String[] args) {
    		
    		FileReader fileReader = null;
    
    		try {
    			fileReader = new FileReader("D:\\Java课程\\教案\\09-java基础语法\\11.txt");
    			
    //			char[] chr = new char[3];
    //			int i = fileReader.read(chr);
    			
    //			System.out.println(Arrays.toString(chr));
    			
    			char[] chr = new char[3];
    			int e = -1;
    			while ((e = fileReader.read(chr)) != -1) {
    //				System.out.println(e);
    				System.out.println(Arrays.toString(chr));
    			}
    			
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} finally {
    			if(fileReader != null) {
    				try {
    					fileReader.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}	
    	}
    
  • 高效缓存区输入流

    BufferedReader

    从字符输入流中读取文本,缓冲各个字符,从而实现字符,数组和行的高效读取

    行读取:readLine()

    public static void main(String[] args) {
    		
    		BufferedReader reader = null;
    		
    		try {
    			reader = new BufferedReader(new FileReader("D:\\\\Java课程\\\\教案\\\\09-java基础语法\\\\11.txt"));
    //			String str = reader.readLine();
    //			System.out.println(str);
    			String sign = null;
    			
    			while((sign = reader.readLine()) != null) {
    				System.out.println(sign);
    			}
    			
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} finally {
    			if(reader != null) {
    				try {
    					reader.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    		
    	}
    
  • 高效缓存区输出流

    BufferedWriter

    写换行符: newLine()

    public static void main(String[] args) {
    	
    		BufferedWriter writer = null;
    		
    		try {
    			writer = new BufferedWriter(new FileWriter("D:\\Java课程\\教案\\09-java基础语法\\11.txt", true));
    			writer.newLine();
    			writer.write("asfa11");
    			writer.newLine();
    			writer.write("dsgadg");
    			
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} finally {
    			if(writer != null) {
    				try {
    					writer.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    		
    	}
    

4、字节流

  • 字节输入流

    InputStream

    常用子类:FileInputStream

    public static void main(String[] args) {
    		
    		InputStream input = null;
    		
    		try {
    			input = new FileInputStream("D:/Java课程/教案/09-java基础语法/11.txt");
    			
    			byte[] b = new byte[3];
    			
    			int len = -1;
    			while((len = input.read(b)) != -1) {
    				System.out.println(new String(b, 0, len));
    			}
    			
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} finally {
    			if(input != null) {
    				try {
    					input.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    		
    	}
    
  • 字节输出流

    OutputStream

    常用子类:FileOutputStream

    public static void main(String[] args) {
    		
        FileOutputStream output = null;
    
        try {
            output = new FileOutputStream("D:/Java课程/教案/09-java基础语法/11.txt");
    
            output.write(104);
            output.write(new byte[] {101,102,103});
    
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    
    }
    
  • 高效缓冲字节流

    BufferedInputStream

    BufferedOutputStream

    public static void main(String[] args) {
    		
    		InputStream input = null;
    		OutputStream out = null;
    		
    		try {
    			input = new BufferedInputStream(new FileInputStream("D:/Java课程/教案/10-java基础语法/3.jpg"));
    			out = new BufferedOutputStream(new FileOutputStream("D:/Java课程/教案/10-java基础语法/4.jpg"));
    			
    			byte[] bt = new byte[1024];
    			
    			int i = -1;
    			while((i = input.read(bt)) != -1) {
    				out.write(bt, 0, i);
    			}
    			
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} finally {
    			try {
    				if(input != null) {
    					input.close();
    				}
    				if(out != null) {
    					out.close();
    				}
    			} catch (Exception e2) {
    				// TODO: handle exception
    			}
    		}
    		
    	}
    

5、字节流和字符流的转换

  • OutputStreamWriter
  • InputStreamReader
public static void main(String[] args) {
		
		OutputStreamWriter out = null;
		InputStreamReader in = null;
		
		try {
			out = new OutputStreamWriter(new FileOutputStream("D:/Java课程/教案/10-java基础语法/1.txt"), "GBK");
			out.write("你好");
			out.flush();
			
			in = new InputStreamReader(new FileInputStream("D:/Java课程/教案/10-java基础语法/1.txt"), "GBK");
			char[] chr = new char[100];
			in.read(chr);
			
			System.out.println(new String(chr));
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(out != null) {
					out.close();
				}
				if(in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
	}

6、打印流

PrintWriter

	public static void main(String[] args) {

		PrintWriter pw = null;
		
		try {
			pw = new PrintWriter("D:/Java课程/教案/10-java基础语法/1.txt");
			pw.println("hello");
			pw.println("world");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(pw != null) {
				pw.close();
			}
		}	
	}

7、序列化流(对象流)

序列化就是一种用来处理对象对象流的机制,所有对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可以将流化后的对象传输与网络之间。序列化是为了解决在对象流进行读写操作时所引发的问题。

把对象以流的形式存储在硬盘或者数据库中的过程就是写序列化流

public static void main(String[] args) {
		
		Person person = new Person("张三", 18);
		
		ObjectOutputStream outputStream = null;
		
		ObjectInputStream inputStream = null;
		
		try {
			outputStream = new ObjectOutputStream(new FileOutputStream("D:/Java课程/教案/10-java基础语法/person.txt"));
			outputStream.writeObject(person);
			
			inputStream = new ObjectInputStream(new FileInputStream("D:/Java课程/教案/10-java基础语法/person.txt"));
			Object object = inputStream.readObject();
			Person person2 = (Person)object;
			
			System.out.println(person2.toString());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(outputStream != null) {
					outputStream.close();
				}
				if(inputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
字节流字符流的区别在于,字节流以字节为单位进行读写操作,而字符流以字符为单位进行读写操作。字节流能够处理所有类型的数据,包括文本、图像、音频等,但是对于文本处理来说,字节流需要考虑编码问题。而字符流则专门用于处理文本数据,可以自动处理编码相关的问题。 实现字节流字符流转换可以使用InputStreamReader和OutputStreamWriter类,将字节流转换字符流,或者将字符流转换字节流。具体代码如下: ```java // 将字节流转换字符流 InputStream inputStream = new FileInputStream("input.txt"); Reader reader = new InputStreamReader(inputStream, "UTF-8"); // 将字符流转换字节流 OutputStream outputStream = new FileOutputStream("output.txt"); Writer writer = new OutputStreamWriter(outputStream, "UTF-8"); ``` 对象序列化是指将对象转换为字节序列的过程,反序列化则是将字节序列转换对象的过程。Java提供了ObjectOutputStream和ObjectInputStream类来实现对象序列化和反序列化。具体代码如下: ```java import java.io.*; public class SerializationDemo { public static void main(String[] args) { // 序列化对象 try { FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); Employee e = new Employee("Tom", "Developer", 10000); out.writeObject(e); out.close(); fileOut.close(); System.out.println("Serialized data is saved in employee.ser"); } catch (IOException i) { i.printStackTrace(); } // 反序列化对象 try { FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Employee e = (Employee) in.readObject(); in.close(); fileIn.close(); System.out.println("Deserialized data: " + e.toString()); } catch (IOException i) { i.printStackTrace(); } catch (ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); } } } class Employee implements Serializable { private String name; private String job; private double salary; public Employee(String name, String job, double salary) { this.name = name; this.job = job; this.salary = salary; } public String getName() { return name; } public String getJob() { return job; } public double getSalary() { return salary; } public String toString() { return "Name: " + name + ", Job: " + job + ", Salary: " + salary; } } ``` 以上代码中,Employee类实现了Serializable接口,使得其可以被序列化。在序列化过程中,使用ObjectOutputStream将Employee对象写入文件中;在反序列化过程中,使用ObjectInputStream将文件中的字节流读取出来,并将其转换为Employee对象

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值