Java第六章第4节:输入输出流( I/O流) 文件 读写二进制文件

简介

👨‍💻个人主页@云边牧风
👨‍🎓小编介绍:欢迎来到云边牧风破烂的小星球🌝
📋专栏:Java基础知识
🔑本章内容:输入输出流
记得 评论📝 +点赞👍 +收藏😽 +关注💞哦~

这一节的主要内容有:

随机存取文件

RandomAccessFile

标准输入输出的重定向

序列化与对象克隆

一、随机存取文件

概念:

很多情况下,要求程序能够迅速、直接地访问文件中的特定信息,这时就需要用到“随机存取文件”——可以理解为插入式地进行读写

流文件 往往是 依次、顺序 读取的,要想查询某部分特定信息,必须从头读一遍文件,直到找到位置
随机存取文件 能够方便的 直接定位 到特定位置

①随机存取文件必须要指定格式规则

最简单 的格式 是要求文件中的所有记录 均保持相同的固定长度 ,这样程序可以容易地计算出任何一条记录相对于文件头的确切位置

RandomAccessFile用于随机存取文件

创建文件
读写文件
关闭文件

二、RandomAccessFile

RandomAccessFile类的特点

可跳转到文件的任意位置读 / 写数据
可在随机文件中 插入数据 ,而不破坏该文件的其他数据;
在等长记录格式文件的随机读取时有很大的优势,但 仅限于操作文件 ,不能访问其它 IO 设备,如网络、内存映像等;

有个位置指示器,指向当前读写处的位置。刚打开文件时,文件指示器指向文件的开头处。对文件指针显式操作的方法有:

public int skipBytes (int n)// 把文件指针 向前移动指定的 n 个字节

 

public void seek (long)// 移动文件指针到指定的位置

 

public native long getFilePointer ()// 得到当前的文件指针

RandomAccessFile类的构造方法

RandomAccessFile(File file,String mode) throws FileNotFoundException

 

RandomAccessFile(String name, String mode) throws FileNotFoundException

 

mode 指明 要执行操作的权限 :只读 / 读写( r/ rw

RandomAccessFile类的常用方法

length () :返回 文件的长度 ,即字节数
read () :从文件中读取一 字节, 遇到结尾,则返回 -1
readDouble () :读取八个字节 ( double 数据 )
writeChar (int v) :写入一个 字符 ,两个字节,高位先写入
writeInt (int v) :写入四个字节的 int 型数字

如:10个整数写入tom.dat文件中,然后反序读出

import java.io.*;
public class Main {
   public static void main(String args[]) {
      RandomAccessFile inAndOut=null;
      int data[]={1,2,3,4,5,6,7,8,9,10};
      try{ inAndOut=new RandomAccessFile("tom.dat","rw");
           for(int i=0;i<data.length;i++) {
              inAndOut.writeInt(data[i]);
           } 
           for(long i=data.length-1;i>=0;i--) { 
              inAndOut.seek(i*4);       
              System.out.printf("\t%d",inAndOut.readInt()); 
           }
           inAndOut.close();
      }
      catch(IOException e){} 
   }
}

对于    inAndOut.seek(i*4);       有👇:

一个int型数据占4个字节,inAndOut从文件的第37个字节读取最后面的一个整数,每隔4个字节往前读取一个整数

三、标准输入输出的重定向

标准输入输出的重定向

——可以通过“重定向改变inouterr默认对应的输入/输出设备

setIn ( InputStream ) : 设置标准 输入

 

setOut ( PrintStream ) :设置标准 输出

 

setErr ( PrintStream ) :设置标准 错误输出

例如:

import java.io.*;
public class Main {
   public static void main(String args[]) {
        BufferedInputStream inn = new BufferedInputStream(new FileInputStream( 
        "d:\\1234567890\\input.java" ));
        PrintStream outt = new PrintStream(new BufferedOutputStream(new                     
        FileOutputStream("d:\\1234567890\\test.out") ) );
        System.setIn(inn);
        System.setOut(outt);
        System.setErr(outt);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        System.out.println(s);
        outt.close(); 

   }
}

//首先从input.java中读取一行;然后输出到test.out文件中。

四、序列化与对象克隆

CloneClass a=new CloneClass();

a.aInt=10;

CloneClass b=(CloneClass)a.clone();

System.out.println(b.aInt);

五、练习

练习1

        在D:\1234567890\grade.txt中保存了一个学生的多门课程,需要从该文件读取学生的成绩,并将课程成绩按照从高到低的顺序排列,将排序后的成绩保存到D:\1234567890\sortgrade.txt中。

 可以参考如下代码:

练习2

        在D:\1234567890\newFile文件夹下存放有两类文件:.txt文本文件和.jpg图片文件。现在需要将D:\1234567890\newFile文件夹中的.txt文件中的内容读出并显示到屏幕,将D:\1234567890\newFile文件夹中的.jpg图片文件复制到D:\newFile文件夹中。然后删除D:\1234567890\newFile文件夹中的所有文件。

public void MoveFiles() throws SQLException, IOException{
		File file=new File(“D:\\1234567890\\newFile");
		File[] filenames=file.listFiles();
		for(int i=0;i<filenames.length;i++){
		    if(filenames[i].getName().endsWith(“.txt”)){ //输出txt文件内容
		        BufferedReader read=new BufferedReader(
                                    new FileReader(file+"\\"+filenames[i].getName()));
		        String  newline=read.readLine();
		        while(newline!=null){
		            System.out.println(newline); 
		            newline=read.readLine();
		        }
		        read.close();
            }
		
		    else{  //移动jpg文件
		        BufferedInputStream input=new BufferedInputStream(
               new FileInputStream("D:\\1234567890\\newFile\\"+filenames[i].getName()));
		        BufferedOutputStream output=new BufferedInputStream(
              new FileOutputStream("D:\\newFile\\"+filenames[i].getName()));
		        int in=input.read();
		        while(in!=-1){
		            output.write(in);
		            in=input.read();
		        }
		        output.flush();
		        output.close();
		        input.close();
		    }
		}
		for(int j=0;j<filenames.length;j++){ //删除文件夹中所有文件
		    filenames[j].delete();
		}
	}

六、本章总结:

输入 / 输出流

    I/O流类

文件读写

    读写文本文件

    读写二进制文件

    随机文件读写

结束语:

以上是Jav第六章的全部内容 希望大家喜欢

下一节讲第7章——线程与JDBC

喜欢的可以点赞+关注哈 ❤

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云边牧风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值