一、缓冲流(处理流的一种)

1.作用:可以提高文件操作的效率

2.使用BufferedInputStream和BufferedOutputStream实现非文本文件的复制

特点:flush()方法

代码示例:

        BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try{
//1.提供读入、写入的文件
File file1 = new File("awsl.jpg");
File file2 = new File("awysl.jpg");
//2.创建相应节点流FileInputStream、FileOutputStream
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
//3.将节点流的对象作为形参传到缓冲流的构造器中
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//4.具体的文件复制操作
byte[] b = new byte[];
int len;
while((len = bis.read(b)) != -){
bos.write(b,,len);
bos.flush();//把最后一点数据清空出去。
}
}catch(IOException e){
e.printStackTrace();
}finally{
//关闭流(只需要关闭缓冲流)
if(bis != null){
try{
bis.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(bos != null){
try{
bos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

2.使用BufferedReader和BufferedWriter实现纯文本文件的复制(纯文本文件才使用字符流,doc文件不是纯文本,只能使用字节流)

特点:使用BufferedReader的readLine()方法读取文件的一行

   BufferedWriter的flush()方法

代码示例:

        BufferedWriter bw = null;
BufferedReader br = null;
try{
File file1 = new File("hello.txt");
File file2 = new File("hello2.txt");
FileReader fr = new FileReader(file1);
FileWriter fw = new FileWriter(file2);
br = new BufferedReader(fr);
bw = new BufferedWriter(fw); String str;
//使用bufferedReader的readLine()方法读取文件的一行,返回str类型的值。
while((str = br.readLine()) != null){//注意:读取结束返回null
bw.write(str);//也可以这么换行:bw.write(str+"\n");
bw.newLine();//换行
bw.flush();
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br != null){
try{
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(bw != null){
try{
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

二、转换流(处理流的一种)

1.作用:提供了在字节流和字符流之间的转换;字节流中的数据都是字符时,转换成字符流操作更加高效。

2。代码示例:

解码:字节流 - - ->字符流

编码:字符流 - - ->字节流

        BufferedWriter bw = null;
BufferedReader br = null;
try{
//解码
File file1 = new File("hello.txt");
FileInputStream fis = new FileInputStream(file1);
InputStreamReader isr = new InputStreamReader(fis,"GBK");//按GBK的编码标准转换
br = new BufferedReader(isr);
//编码
File file2 = new File("hello3.txt");
FileOutputStream fos = new FileOutputStream(file2);
OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
bw = new BufferedWriter(osw); String str;
while((str = br.readLine()) != null){
bw.write(str);
bw.newLine();
bw.flush();
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br != null){
try{
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(bw != null){
try{
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

三、标准输入输出流

标准的输入流:System.in

标准的输出流:System.out

题目:

  从键盘输入字符串,要求将读取的整行字符串转成大写输出,然后继续输入操作,直到输入“e”或“exit”时退出程序。

代码:

        BufferedReader br = null;
try{
InputStream is = System.in;//System.in返回一个InputStream类型的对象
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr); String str;
while(true){
System.out.println("请输入字符串:");
str = br.readLine();
if(str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")){
break;
}
String str1 = str.toUpperCase();
System.out.println(str1);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br != null){
try{
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

四、打印流(处理流的一种)

1.分类

字节流:PrintStream

字符流:PrintWriter

2.代码示例

        FileOutputStream fos = null;
try{
fos = new FileOutputStream(new File("print.txt"));
}catch(IOException e){
e.printStackTrace();
}
//创建打印输出流,设置为自动刷新模式(写入换行符或字节"\n"时都会刷新输出缓冲区
PrintStream ps = new PrintStream(fos,true);
if(ps != null){
System.setOut(ps);//把标准输出流(控制台输出)改为输出到文件
}
for(int i = ;i <= ;i++){//输出ASCII字符
System.out.print((char)i);
if(i % == ){
System.out.println();//每50个数据换行
}
}
ps.close();

五、数据流(处理流的一种)

1.作用

  为了方便的操作Java语言的基本数据类型、String和字节数组类型的数据,可以使用数据流。

2.特点

DataInputStream和DataOutputStream分别套接在InputStream和OutputStream节点流上。

2.DataOutputStream的使用

注意:输出的物理文件中的内容会变成一堆乱码,需要通过DataInputStream来读取。

        DataOutputStream dos = null;
try{
dos = new DataOutputStream(new FileOutputStream(new File("data.txt")));
dos.writeUTF("我爱你,而你却不知道!");//writeUTF()用来写入String
dos.writeBoolean(true);
dos.writeLong();
}catch(IOException e){
e.printStackTrace();
}finally{
if(dos != null){
try{
dos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

3.DataInputStream的使用

        DataInputStream dis = null;
try{
dis = new DataInputStream(new FileInputStream(new File("data.txt")));
String str = dis.readUTF();
System.out.println(str);//输出"我爱你,而你却不知道!"
Boolean b = dis.readBoolean();
System.out.println(b);//输出true
Long l = dis.readLong();
System.out.println(l);//输出310973560
}catch(IOException e){
e.printStackTrace();
}finally{
if(dis != null){
try{
dis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

六、对象流(处理流之一)

1.作用

  用于存储和读取对象的处理流。

2.特点

序列化(Serialize):用ObejctOutPutStream类将一个Java对象写入IO流中。

反序列化(Deserialize):用ObjectInputStream类从Io流中恢复该Java对象。

对象的序列化机制:

  对象的序列化机制允许把内存中的Java对象转换成与平台无关的二进制流,从而允许把这种二进制流持久的保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。

当其他程序获取了二进制流,就可以重新恢复成Java对象。

  对象支持序列化机制的前提:

  (1)类需要实现如下两个接口之一:Serializable Externalizable

  (2)类的属性也要实现Serializable。

  (3)提供一个版本号:private static final long serialVersionUID

  (4)使用static和transient关键字修饰的变量不可实现序列化(运行不会报错,但读取出来属性值为null)

3.序列化过程

class Person implements Serializable{
private static final long SerialVersionUID = 1234561234L;//版本号
String name;
Integer age;
static String ability;//static修饰的变量不可序列化
Person(String name, Integer age,String ability){
this.name = name;
this.age = age;
this.ability = ability;
}
@Override
public String toString(){
return "Person[name="+name+",age="+age+",ability="+ability+"]";
}
}
class Test{
public static void main(String[] args){ Person p1 = new Person("小明",,"swimming");
Person p2 = new Person("超人",,"flying"); ObjectOutputStream oos = null;
try{
oos = new ObjectOutputStream(new FileOutputStream(new File("object.txt")));
oos.writeObject(p1);
oos.flush();
oos.writeObject(p2);
oos.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
if(oos != null){
try{
oos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}

4.反序列化过程

class Test{
public static void main(String[] args){ ObjectInputStream ois = null;
try{
ois = new ObjectInputStream(new FileInputStream(new File("object.txt")));
Person p1 = (Person)ois.readObject();
System.out.println(p1);//输出Person[name=小明,age=23,ability=null]
Person p2 = (Person)ois.readObject();
System.out.println(p2);//输出Person[name=超人,age=21,ability=null]
}catch(Exception e){
e.printStackTrace();
}finally{
if(ois != null){
try{
ois.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}

七、RandomAccessFile(处理流)

1. 作用

  支持“随机访问”的方式,程序可以直接跳到文件的任意位置来读、写文件;

  支持只访问文件的部分内容;

  可以向已存在的文件内容后追加内容。

2.特点

创建RandomAccessFile类实例需要指定一个mode参数,指定文件访问模式:

  r:以只读方式打开

  rw:可读取、写入

  rwd:可读取、写入;同步文件内容的更新

  rws:可读取、写入;同步文件内容和元数据的更新

RandomAccessFile对象包含一个记录指针,标识当前读写处的位置,这个指针可以自由移动。

  long getFilePointer():获取文件记录指针的当前位置。

  void seek(long pos):将文件记录指针定位到pos位置。

3.文件的读写操作

        RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try{
raf1 = new RandomAccessFile(new File("hello.txt"),"r");//只读方式打开
raf2 = new RandomAccessFile(new File("hello6.txt"),"rw");//读写方式打开
byte[] b = new byte[];
int len;
while((len = raf1.read(b)) != -){
raf2.write(b,,len);
}
}catch(IOException e){
e.printStackTrace();
}finally{
//关闭流
if(raf1 != null){
try{
raf1.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(raf2 != null){
try{
raf2.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

4.从任意位置写入数据(会覆盖原有的数据,而不是插入数据)

        RandomAccessFile raf = null;

        try{
raf = new RandomAccessFile(new File("hello6.txt"),"rw"); raf.seek();//定位到3的位置,默认在0
raf.write("haha".getBytes());//原来的数据:The destination is stars and seas!
//写入后的数据:Thehahatination is stars and seas!
}catch(IOException e){
e.printStackTrace();
}finally{
//关闭流
if(raf != null){
try{
raf.close();
}catch(IOException e){
e.printStackTrace();
}
} }

5.从任意位置插入数据,不会覆盖插入位置后面的数据

        RandomAccessFile raf = null;

        try{
raf = new RandomAccessFile(new File("hello6.txt"),"rw"); raf.seek();
byte[] b = new byte[];
int len;
StringBuffer sb = new StringBuffer();
while((len = raf.read(b)) != -){
sb.append(new String(b,,len));//把要插入的位置后面的数据都读取到sb中。
}
raf.seek();
raf.write("haha ".getBytes());//原来的数据:The destination is stars and seas!
raf.write(sb.toString().getBytes());//结果:The haha destination is stars and seas!
}catch(IOException e){
e.printStackTrace();
}finally{
//关闭流
if(raf != null){
try{
raf.close();
}catch(IOException e){
e.printStackTrace();
}
} }

Java语法基础学习DayFifteen(IO续)的更多相关文章

  1. Java语法基础学习DayFourteen(IO)

    一.java.io.FIle类 1.特点 (1)凡是与输入.输出相关的类.接口等都定义在java.io包下. (2)File是一个类,使用构造器创建对象,此对象对应一个文件(.txt .avi .do ...

  2. Java语法基础学习DayTwenty(反射机制续)

    一.Java动态代理 1.代理设计模式的原理 使用一个代理将对象包装起来, 然后用该代理对象取代原始对象. 任何对原始对象的调用都要通过代理. 代理对象决定是否以及何时将方法调用转到原始对象上. 2. ...

  3. Java语法基础学习DaySeventeen(多线程续)

    一.线程的特点 1.线程的分类 java中的线程分为两类:守护线程和用户线程.唯一的区别是判断JVM何时离开. 守护线程是用来服务用户线程的,通过在start()方法前调用Thread.setDaem ...

  4. Java语法基础学习DayTen(集合续)

    一.集合 1.Set:存储的元素是无序的.不可重复的 (1)无序性:无序性不等于随机性,无序指的是元素在底层存储的位置是无序的. (2)不可重复性:当向Set中添加相同的元素时,后添加的元素不能添加进 ...

  5. Java语法基础学习DayTwentyOne(网络编程)

    一.IP地址和端口号 1.作用 通过IP地址,唯一的定位互联网上一台主机. 端口号标识正在计算机上运行的进程,不同进程有不同的端口号,被规定为一个16位的整数0~65535,其中0~1023被预先定义 ...

  6. Java语法基础学习DayEighteen(常用类)

    一.String类 1.特点 String代表不可变的字符序列,底层用char[]存放. String是final的. 2.内存解析 3.常用方法 int length() char charAt(i ...

  7. Java语法基础学习DaySeven

    ---恢复内容开始--- 一.包装类——Wrapper 1.定义:针对八种基本数据类型定义相应的引用类型——包装类(封装类) boolean——Boolean          byte——Byte ...

  8. Java语法基础学习DaySix

    一.JavaBean——可重用组件 1.JavaBean是指符合以下标准的Java类: (1)类是公共的 (2)有一个无参的公共的构造器 (3)有属性,且有对应的get.set方法 2.好处 用户可以 ...

  9. Java语法基础学习DayThree

    一.流程控制语句补充 1.switch语句 格式: switch(表达式) { case 值1: 语句体1; break; case 值2: 语句体2; break; ... default: 语句体 ...

随机推荐

  1. 对字符串md5加密

    public String getMD5(String str) { try { // 生成一个MD5加密计算摘要 MessageDigest md = MessageDigest.getInstan ...

  2. 7.mongo python 库 pymongo的安装

    1.Python 中如果想要和 MongoDB 进行交互就需要借助于 PyMongo 库,在CMD中使用命令即可[注意此处是pip3,pip无法安装]: pip3 install pymongo 2. ...

  3. arcgis 制图-插值图

    1.生成插值图 插值工具: 方案1:Spatial Analyst 工具-->插值分析-->反距离权重法 (IDW) + Spatial Analyst 工具-->提取分析--> ...

  4. Python数据分析Numpy库方法简介(一)

    Numpy功能简介: 1.官网:www.numpy.org 2.特点:(1)高效的多维矩阵/数组; (2);复杂的广播功能 (3):有大量的内置数学统计函数 矩阵(多维数组): 一维数组:  ([ 值 ...

  5. WIN10下,JAVA安装及环境变量配置(cmd可以运行java,却不能运行javac)

    1.安装JDK 选择安装目录 安装过程中会出现两次 安装提示 . 第一次是安装 jdk ,第二次是安装 jre .建议两个都安装在同一个java文件夹中的不同文件夹中.(不能都安装在java文件夹的根 ...

  6. FL Studio的模式剪辑是什么?

    FL Studio里的模式剪辑功能里,有一个模式菜单.模式剪辑菜单和模式选择器面板.模式可以作为模式剪辑放置在播放列表中,模式剪辑的名称显示在剪辑的标题栏中.(注意:模式注释和事件自动化可以共享相同的 ...

  7. HTTP的简单的解析

    HTTP 中文全称为超文本传输协议是一种为分布式,合作式,多媒体信息系统服务,面向应用层的协议.它是一种通用的,不分状态(stateless)的协议,除了诸如名称服务和分布对象管理系统之类的超文本用途 ...

  8. Bootstrap3基础 warning/active... 表格的状态类(不同的背景色)

      内容 参数   OS   Windows 10 x64   browser   Firefox 65.0.2   framework     Bootstrap 3.3.7   editor    ...

  9. Python3 tkinter基础 Menu add_cascade 多级菜单 add_separator 分割线

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  10. pandas之时间序列

    Pandas中提供了许多用来处理时间格式文本的方法,包括按不同方法生成一个时间序列,修改时间的格式,重采样等等. 按不同的方法生成时间序列 In [7]: import pandas as pd # ...