Java-day13(IO流)

IO流

凡是与输入,输出相关的类,接口等都定义在java.io包下
在这里插入图片描述

1.File类的使用

  • File类可以有构造器创建其对象,此对象对应着一个文件(.txt,.avi,.doc,.mp3等)或文件目录

  • File类对象是与平台无关的

  • File中的方法仅涉及到如何创建,删除,重命名等操作,不涉及文件内容的修改(需IO流来操作)

  • File类对象常作为io流的具体类的构造器的形参

常见的方法
在这里插入图片描述
熟练掌握红色标记的方法
例:

import java.io.File;
import java.sql.Date;import org.junit.Test;
public class test10{@Testpublic void test1(){//绝对路径File f1 = new File("C:/Users/Cat God 007/Desktop/hello.txt"); //文件File f2 = new File("C:/Users/Cat God 007/Desktop");//文件目录//相对路径File f3 = new File("hello.txt");System.out.println("=============访问文件名================");System.out.println(f3.getName());//返回文件名          System.out.println(f3.getPath());//返回文件路径System.out.println(f3.getAbsoluteFile());//返回文件的绝对路径System.out.println(f3.getParent());//返回上一级文件目录System.out.println(f3.getAbsolutePath());//返回完整的文件路径System.out.println("=============================");System.out.println(f2.getName());//返回文件目录名System.out.println(f2.getPath());//返回文件目录路径System.out.println(f2.getAbsoluteFile());//返回文件目录的绝对路径System.out.println(f2.getParent());//返回上一级文件目录System.out.println(f2.getAbsolutePath());//返回完整的文件目录路径System.out.println("============文件检测=========");System.out.println(f1.exists());//检测文件是否存在System.out.println(f1.canRead());//检测文件是否可读System.out.println(f1.canWrite());//检测文件是否可写System.out.println(f1.isFile());//检测此对象是否不是文件System.out.println(f1.isDirectory());//检测此对象是否不是文件目录System.out.println("============获取常规文件信息=========");System.out.println(new Date(f1.lastModified()));//获取文件最后修改时间System.out.println(f1.length());//获取文件大小}@Testpublic void test2(){File f1 = new File("C:/Users/Cat God 007/Desktop/hello.txt"); File f2 = new File("C:/Users/Cat God 007/Desktop/test/tes1-test9");System.out.println(f1.delete());//删除文件if(!f1.exists()){boolean b1 = f1.createNewFile();//创建文件System.out.println(b1);}if(!f2.exists()){boolean b2 = f2.mkdir();//mkdirs()可以递归创建文件夹,mkdir只创建最后的文件目录,若它上层没有创建,则它也不会创建System.out.println(b2);}File f3 = new File("C:\\Users\\Cat God 007\\Desktop\\javacode\\day13");String[] list = f3.list();for(int i = 0;i < list.length;i++){System.out.println(list[i]);//以String方式读取出f3下的文件}File[] files = f3.listFiles();for(int i = 0;i < files.length;i++){System.out.println(files[i].getName());//以文件方式读取出f3下的文件}}
}

2.IO流原理及其分类

  • IO流用来处理设备之间的数据传输
  • 按数据单位可分为:字节流(8bit)字符流(16bit)
  • 按流的流向可分为:输入流输出流
  • 按流的角色可分为:节点流(直接作为于文件),处理流
抽象基类字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter
	IO流设计40多个类,都是从以上4个抽象基类派生由这四个类派生出的子类名称都是以其父类名作为子类名后缀

IO流体系

在这里插入图片描述

  • 访问文件的类也被称为节点流,文件流,其他类被称为处理流

3.文件流

FileInputStream

例:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.Test;public class test11{@Test
//读取硬盘文件内容到程序中,使用FileInputStream(读取的文件一定要存在,否则会报文件找不到的异常)
public void test1()throws Exception{//1.创建Filen类型的对象File file = new File("hello.txt");//2.创建FileInputStream类型的对象FileInputStream files = new FileInputStream(file);      //3.调用FileInputStream的方法,实现file文件的读取//read():读取文件的一个字节,当执行到文件结尾时,返回-1//方式一int b = files.read();while(b != -1){System.out.println((char)b);//int转字符(否则打印出来的是对应的Ascll码)b = files.read();}//方式二int c;while((c = files.read()) != -1){System.out.println((char)c);}//4.关闭相应的流files.close();
}@Test//测试test1的优化,确保每次流都能被关闭public void test2(){FileInputStream files = null;try {File file = new File("hello.txt");files = new FileInputStream(file);int c;while((c = files.read()) != -1){System.out.println((char)c);}} catch (IOException e) {e.printStackTrace();}finally{if(files != null){try{files.close();}catch(IOException e){e.printStackTrace();}}
}
}@Testpublic void test3(){FileInputStream files = null;try{File file = new File("hello.txt");files = new FileInputStream(file);byte[] b = new byte[5];//将读取到的数据写入数组中int len;//每次读入到byte中的字节长度while((len = files.read(b)) != -1){// 方式一:运行for循环实现遍历输出// 成功案例:for(int i = 0;i < len;i++){System.out.print((char)b[i]);}//错误案例:使用b.length时,在读取到最后(此时只读取了1个元素),但依旧会传入5个元素的数组{1个新元素+4个旧元素}// for(int i = 0;i < b.length;i++){//     System.out.print((char)b[i]);// }//方式二:运行String构造器实现遍历输出// String str = new String(b, 0, len);// System.out.println(str);}}catch(IOException e){e.printStackTrace();}finally{if(files != null){try{files.close();}catch(IOException e){e.printStackTrace();}}}}
}

FileOutputStream

简单编写

import java.io.File;
import java.io.FileOutputStream;
import org.junit.Test;public class test12{@Testpublic void testFileOutputSteam(){//1.创建要写入文件的文件路径的File对象,此文件路径可以不存在(会自动创建),若存在,就会用新写入的数据覆盖原来的数据File file = new File("hello1.txt");//2.创建FileOutputStream对象,将之前的File对象作形参传入FileOutputStream的构造器中FileOutputStream f = null;try{   f = new FileOutputStream(file);//3.写入数据f.write(new String("I Love China").getBytes());//这里用到了字符串转字节数组}catch(Exception e){e.printStackTrace();}finally{//关闭输出流if(f != null){try{f.close();}catch(Exception e){e.printStackTrace();}}}}
}

练习:编写非文本文件复制的方法
主要实现

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.junit.Test;public class test12{@Test//从硬盘中读入数据,将此数据写入到另一位置(相当文件复制)public void testFileInputOutputSteam(){//1.提供读,写的文件路径File file1 = new File("C:\\Users\\Cat God 007\\Desktop\\t1.jpg");File file2 = new File("C:\\\\Users\\\\Cat God 007\\\\Desktop\\\\tt.jpg");//2.提供读,写流FileOutputStream fos = null;FileInputStream fis = null;try{ fis = new FileInputStream(file1);fos = new FileOutputStream(file2);//3.实现文件复制byte [] b = new byte[20];int len;while ((len = fis.read(b)) != -1) {fos.write(b,0,len);                }}catch(Exception e){e.printStackTrace();}finally{//4.关闭读,写流if(fos != null){try{fos.close();}catch(Exception e){e.printStackTrace();}}if(fis != null){try{fis.close();}catch(Exception e){e.printStackTrace();}}}}

最后包装成方法,并进行测试

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;public class test12{public static void main(String[] args) {  testFileInputOutputSteam("C:\\Users\\Cat God 007\\Desktop\\t1.jpg", "C:\\Users\\Cat God 007\\Desktop\\tt1.jpg");}public static void testFileInputOutputSteam(String src,String dest){File file1 = new File(src);File file2 = new File(dest);FileOutputStream fos = null;FileInputStream fis = null;try{fis = new FileInputStream(file1);fos = new FileOutputStream(file2);byte [] b = new byte[20];int len;while ((len = fis.read(b)) != -1) {fos.write(b,0,len);                }}catch(Exception e){e.printStackTrace();}finally{if(fos != null){try{fos.close();}catch(Exception e){e.printStackTrace();}}if(fis != null){try{fis.close();}catch(Exception e){e.printStackTrace();}}}}

FileReader,FileWriter(字符流)

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import org.junit.Test;public class test13{//使用FileReader,FileWriter可以实现文本文件的复制@Testpublic void testFileReaderWriter(){    FileReader fr = null;FileWriter fw = null; try{File src = new File("hello.txt");//读File desc = new File("hello1.txt");//写fr = new FileReader(src);fw = new FileWriter(desc);char[] c = new char[20];int len;while ((len = fr.read(c)) != -1) {fw.write(c,0,len);                }}catch(Exception e){e.printStackTrace();}finally{if(fr != null){try{fr.close();}catch(Exception e){e.printStackTrace();}}if(fw != null){try{fw.close();}catch(Exception e){e.printStackTrace();}}}
}
}
  • 文本文件用字符流,非文本文件(视频文件,音频文件,图片)用字节流,效率较高

4.缓冲流(主要使用)

  • 可以提高处理数据的效率

  • 每次处理完后,都需要刷新(flush())数组,方便下次元素不够写入的情况

使用 BufferedInputStream,BufferedOutputStream 实现非文本文件的复制

例:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.junit.Test;public class test14{@Testpublic void testBufferedInputOutputStream(){BufferedInputStream bis = null;BufferedOutputStream  bos = null;try{            //1.提供读写文件File file1 = new File("C:\\Users\\Cat God 007\\Desktop\\t1.jpg");File file2 = new File(".\\1.jpg");//2.创建相应的节点流FileInputStream fis = new FileInputStream(file1);FileOutputStream fos = new FileOutputStream(file2);//3.将创建的节点流的对象作为形参传递给缓冲流的构造器中bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(fos);//4.实现文本文件byte[] b = new byte[1024];int len;while ((len = bis.read(b)) != -1) {bos.write(b, 0, len);bos.flush();//刷新一下}}catch(Exception e){e.printStackTrace();}finally{//5.关闭相应的流if(bis != null){try{bis.close();}catch(Exception e){e.printStackTrace();}}if(bos != null){try{bos.close();}catch(Exception e){e.printStackTrace();}}}
}
}
}

使用BufferedReader,BufferedWriter实现文本文件的复制

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.junit.Test;public class test{
// BufferedReader()的readLine()方法(一行一行读)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import org.junit.Test;public class test14{@Testpublic void testBufferedReader(){BufferedReader br = null;BufferedWriter bw = null;try{        File file = new File("hello.txt");File file1 = new File("hell1o.txt");FileReader fr = new FileReader(file);FileWriter fw = new FileWriter(file1);br = new BufferedReader(fr);bw = new BufferedWriter(fw);// char[] c = new char[1024];// int len;// while ((len = br.read(c)) != -1) {//     String str = new String(c, 0, len);//     System.out.print(str);// }String str;while ((str = br.readLine()) != null) {//System.out.println(str);bw.write(str + "\n");//bw.newLine();//换行bw.flush();}}catch(Exception e){e.printStackTrace();}finally{if(bw != null){try{bw.close();}catch(Exception e){e.printStackTrace();}}if(br != null){try{br.close();}catch(Exception e){e.printStackTrace();}}}}
}

5.转换流

  • 提供在字节流和字符流之间的转换

  • 字节流中的数据都是字符时,转换成字符流操作更高效

  • 编码(字符串====>字节数组),解码(字节数组====>字符串)

  • 提供两个转换流InputStreamReader(解码),OutputStreamWriter(编码)

例:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;import org.junit.Test;public class test16{@Testpublic void test1(){BufferedReader br = null;BufferedWriter bw = null;try{ //解码(字节数组====>字符串)File file = new File("hello.txt");FileInputStream fis = new FileInputStream(file);InputStreamReader isr = new InputStreamReader(fis, "UTF-8");br = new BufferedReader(isr);//编码(字符串====>字节数组)File file1 = new File("hello123.txt");FileOutputStream fos = new FileOutputStream(file1);OutputStreamWriter isw = new OutputStreamWriter(fos, "UTF-8");bw = new BufferedWriter(isw);String str;while ((str = br.readLine()) != null) {//System.out.println(str);isw.write(str + "\n");//bw.newLine();//换行isw.flush();}}catch(Exception e){e.printStackTrace();}finally{if(bw != null){try{bw.close();}catch(Exception e){e.printStackTrace();}}if(br != null){try{br.close();}catch(Exception e){e.printStackTrace();}}}}
}

6.标准的输入输出流

  • 标准的输出流:System.out
  • 标准的输入流:System.in

例:
在这里插入图片描述

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;import org.junit.Test;public class test16{@Testpublic void test(){BufferedReader br = null;try{   InputStream is = System.in;//接受传入的字节流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();}}}}
}

练习

在一个目录下创建test.txt文件,并写入以下内容:

云计算是一个比较庞大的概念,入门云计算,首先要从掌握基本概念和基础知识开始,然后通过掌握完全面向云计算的特定供应商的平台或技术等重要领域来增强其专业知识水平,
这样可以更快的学好云计算。你需要学习这些知识:
计算机与网络的基础知识
安全基础知识
编程语言基础
脚本语言
linux基础知识
分布式系统

读取test.txt文件的内容,并打印出来
复制test.txt文件为cloudcompute.txt文件

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;import org.junit.Test;public class test17{@Test//字节流写入文本文件数据public void test1(){BufferedOutputStream bos = null;try{      File file = new File("C:\\Users\\Cat God 007\\Desktop\\test.txt");FileOutputStream fos = new FileOutputStream(file);bos = new BufferedOutputStream(fos);String str = "\u4E91\u8BA1\u7B97\u662F\u4E00\u4E2A\u6BD4\u8F83\u5E9E\u5927\u7684\u6982\u5FF5\uFF0C\u5165\u95E8\u4E91\u8BA1\u7B97\uFF0C\u9996\u5148\u8981\u4ECE\u638C\u63E1\u57FA\u672C\u6982\u5FF5\u548C\u57FA\u7840\u77E5\u8BC6\u5F00\u59CB\uFF0C\u7136\u540E\u901A\u8FC7\u638C\u63E1\u5B8C\u5168\u9762\u5411\u4E91\u8BA1\u7B97\u7684\u7279\u5B9A\u4F9B\u5E94\u5546\u7684\u5E73\u53F0\u6216\u6280\u672F\u7B49\u91CD\u8981\u9886\u57DF\u6765\u589E\u5F3A\u5176\u4E13\u4E1A\u77E5\u8BC6\u6C34\u5E73\uFF0C\r\n" + //"\u8FD9\u6837\u53EF\u4EE5\u66F4\u5FEB\u7684\u5B66\u597D\u4E91\u8BA1\u7B97\u3002\u4F60\u9700\u8981\u5B66\u4E60\u8FD9\u4E9B\u77E5\u8BC6\uFF1A\r\n" + //"\u8BA1\u7B97\u673A\u4E0E\u7F51\u7EDC\u7684\u57FA\u7840\u77E5\u8BC6\r\n" + //"\u5B89\u5168\u57FA\u7840\u77E5\u8BC6\r\n" + //"\u7F16\u7A0B\u8BED\u8A00\u57FA\u7840\r\n" + //"\u811A\u672C\u8BED\u8A00\r\n" + //"linux\u57FA\u7840\u77E5\u8BC6\r\n" + //"\u5206\u5E03\u5F0F\u7CFB\u7EDF";bos.write(str.getBytes());}catch(IOException e){e.printStackTrace();}finally{if(bos != null){try{bos.flush();}catch(Exception e){e.printStackTrace();}}}}@Test//字符流写入文本文件数据public void test2(){BufferedWriter bw = null;try{bw = new BufferedWriter(new FileWriter(new File("C:\\Users\\Cat God 007\\Desktop\\test.txt")));String str = "\u4E91\u8BA1\u7B97\u662F\u4E00\u4E2A\u6BD4\u8F83\u5E9E\u5927\u7684\u6982\u5FF5\uFF0C\u5165\u95E8\u4E91\u8BA1\u7B97\uFF0C\u9996\u5148\u8981\u4ECE\u638C\u63E1\u57FA\u672C\u6982\u5FF5\u548C\u57FA\u7840\u77E5\u8BC6\u5F00\u59CB\uFF0C\u7136\u540E\u901A\u8FC7\u638C\u63E1\u5B8C\u5168\u9762\u5411\u4E91\u8BA1\u7B97\u7684\u7279\u5B9A\u4F9B\u5E94\u5546\u7684\u5E73\u53F0\u6216\u6280\u672F\u7B49\u91CD\u8981\u9886\u57DF\u6765\u589E\u5F3A\u5176\u4E13\u4E1A\u77E5\u8BC6\u6C34\u5E73\uFF0C\r\n" + //"\u8FD9\u6837\u53EF\u4EE5\u66F4\u5FEB\u7684\u5B66\u597D\u4E91\u8BA1\u7B97\u3002\u4F60\u9700\u8981\u5B66\u4E60\u8FD9\u4E9B\u77E5\u8BC6\uFF1A\r\n" + //"\u8BA1\u7B97\u673A\u4E0E\u7F51\u7EDC\u7684\u57FA\u7840\u77E5\u8BC6\r\n" + //"\u5B89\u5168\u57FA\u7840\u77E5\u8BC6\r\n" + //"\u7F16\u7A0B\u8BED\u8A00\u57FA\u7840\r\n" + //"\u811A\u672C\u8BED\u8A00\r\n" + //"linux\u57FA\u7840\u77E5\u8BC6\r\n" + //"\u5206\u5E03\u5F0Fw\u7CFB\u7EDF";bw.write(str);}catch(IOException e){e.printStackTrace();}finally{if(bw != null){try{bw.flush();}catch(Exception e){e.printStackTrace();}}}}@Test//字符流输出文本文件数据public void test3(){BufferedReader br = null;try{br = new BufferedReader(new FileReader("C:\\Users\\Cat God 007\\Desktop\\test.txt"));String str;while((str = br.readLine()) != null){System.out.println(str);}}catch(IOException e){e.printStackTrace();}finally{if(br != null){try{br.close();}catch(IOException e){e.printStackTrace();}}}}@Test//字符流实现复制public void test4(){BufferedWriter bw = null;BufferedReader br = null;try{br = new BufferedReader(new FileReader("C:\\Users\\Cat God 007\\Desktop\\test.txt"));bw = new BufferedWriter(new FileWriter("C:\\Users\\Cat God 007\\Desktop\\cloudcompute.txt"));String str;while((str = br.readLine()) != null){bw.write(str + "\n");}            }catch(IOException e){e.printStackTrace();}finally{if(bw != null){try{bw.close();}catch(IOException e){e.printStackTrace();}}if(br != null){try{br.close();}catch(IOException e){e.printStackTrace();}}}}}

7.打印流

  • PrintStream:字节流 printWriter:字符流

例:

public class test18{@Test//打印流public void printStreamTest(){FileOutputStream fos = null;try{    fos = new FileOutputStream("C:\\Users\\Cat God 007\\Desktop\\test.txt");}catch(IOException e){e.printStackTrace();}//创建打印输出流,设置为自动刷新模式(写入换行符就或字节'\n'时都会刷新输出缓冲区)PrintStream ps = new PrintStream(fos,true);if(ps != null){//把标准输出流改成文件System.setOut(ps);//修改输出打印的位置为ps}for(int i = 0;i < 255;i++){System.out.print((char)i);if(i % 50 == 0){//每50数据一行System.out.println();//换行}}ps.close();}
}

8.数据流

在这里插入图片描述

  • 用来处理基本数据类型,String,字节数组的数据

例:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;import org.junit.Test;public class test19{@Test//数据流写入public void testData(){DataOutputStream dos = null;try {          FileOutputStream fos = new FileOutputStream("C:\\Users\\Cat God 007\\Desktop\\test.txt");dos = new DataOutputStream(fos);dos.writeUTF("你好");dos.writeInt(467876543);dos.writeDouble(1289.789);dos.writeBoolean(true);}catch(IOException e){e.printStackTrace();}finally{if(dos != null){try {dos.close();} catch (IOException e){e.printStackTrace();}}}}@Test//数据流读取public void testData1(){DataInputStream dis = null;try {   dis = new DataInputStream(new FileInputStream("C:\\Users\\Cat God 007\\Desktop\\test.txt"));String str = dis.readUTF();System.out.println(str);int i = dis.readInt();System.out.println(i);double d = dis.readDouble();System.out.println(d);boolean b = dis.readBoolean();System.out.println(b);} catch (IOException e) {e.printStackTrace();}finally{if(dis != null){try {dis.close();} catch (IOException e){e.printStackTrace();}}}}
}

9.对象流

ObjectOutputStream 和 ObjectInputStream

  • 用于存储和读取对象的处理流,可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来

  • 序列化(Serialize):用 ObjectOutputStream 类将Java对象写入IO流中
    在这里插入图片描述

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

  • ObjectOutputStream 和
    ObjectInputStream不能序列化static和transient(短暂的)修饰的成员变量

例:
i

mport java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.junit.Test;public class test20{@Test// 反序列化--ObjectInputStreampublic void testObjectInputStream(){ObjectInputStream ois = null;try {     ois = new ObjectInputStream(new FileInputStream("C:\\\\Users\\\\Cat God 007\\\\Desktop\\\\test.txt"));Person p1 = (Person)ois.readObject();//读取一个对象System.out.println(p1.toString());//打印一个对象Person p2 = (Person) ois.readObject();//读取对象System.out.println(p2);//打印对象}catch (IOException e){e.printStackTrace();}finally{if(ois != null){try{ois.close();}catch (IOException e){e.printStackTrace();}}}}@Test//对象序列化---ObjectOutputStreampublic void testObjectOutputStream(){Person p1 = new Person("张三", 20,new Pet("张二"));Person p2 = new Person("李四", 21,new Pet("李三"));ObjectOutputStream oos = null;try{oos = new ObjectOutputStream(new FileOutputStream("C:\\\\Users\\\\Cat God 007\\\\Desktop\\\\test.txt"));oos.writeObject(p1);oos.flush();oos.writeObject(p2);oos.flush();       }catch(Exception e){e.printStackTrace();}finally{if(oos != null){try {oos.close();} catch (IOException e) {e.printStackTrace();}}}}
}
/** 实现序列化的类:* 1.此类可序列化,需要此类实现Serializable接口* 2.此类可序列化,需要类的属性同样实现Serializable接口* 3.版本号:凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量,表明类的不同版本间的兼容性,如果没有定义,那在运行时会自动生成,如果源码修改,版本号(自动生成的)可能会变化* 如:private static final long serialVersionUID = 1234678876543L;   */
class Person implements Serializable{ private static final long serialVersionUID = 12343128876543L; String name;Integer age;Pet pet;public Person(String name, Integer age,Pet pet) { this.name = name;this.age = age; this.pet = pet;}@Overridepublic String toString() { return "Person{" +"name='" + name + '\'' +", age=" + age + '\'' +", pet=" + pet + '\'' +'}';}
}
class Pet implements Serializable{String name;public Pet(String name) {this.name = name;}
}

10.随机存取文件流

  • RandomAccessFile类支持"随机访问"的方式,程序可以直接跳到文件的任意地方来读,写文件

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

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

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

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

    • void seek(long pos):将文件记录指针定位到pos位置
      在这里插入图片描述

例:

import java.io.RandomAccessFile;import org.junit.Test;public class test21{@Test//进行文件的读,写public void test(){RandomAccessFile raf1 = null;RandomAccessFile raf2 = null;try{    raf1 = new RandomAccessFile("hello.txt","r");raf2 = new RandomAccessFile("hello1.txt","rw");byte[] b = new byte[4];int len;while((len = raf1.read(b))!=-1){raf2.write(b,0,len);}}catch(Exception e){{e.printStackTrace();}}finally{if(raf2 != null){try{raf2.close();}catch(Exception e){e.printStackTrace();}}if(raf1 != null){try{raf1.close();}catch(Exception e){e.printStackTrace();}}}}@Test//在指定位置进行文件的读写,实际上实现的是覆盖的效果public void test1(){RandomAccessFile raf = null;try{raf = new RandomAccessFile("hello.txt","rw");raf.seek(3);//把指针调到第三个的位置raf.write("123456789".getBytes());}catch(Exception e) {e.printStackTrace();}finally{if(raf != null){try{raf.close();}catch(Exception e){e.printStackTrace();}}}}@Test//实现在指定位置的插入效果public void test2(){RandomAccessFile raf = null;try{raf = new RandomAccessFile("hello.txt","rw");raf.seek(3);byte[] b = new byte[10];int len;StringBuffer sb = new StringBuffer();//可变的字符序列,相当于Stringwhile((len = raf.read(b)) != -1){sb.append(new String(b,0,len));}raf.seek(3);//把指针调到第三个的位置raf.write("123456789".getBytes());//写入要插入的内容raf.write(sb.toString().getBytes());//写入原来的后面字符}catch(Exception e) {e.printStackTrace();}finally{if(raf != null){try{raf.close();}catch(Exception e){e.printStackTrace();}}}}@Test//实现在指定位置的插入效果(在test2的基础上进行优化,使之更通用)public void test3(){RandomAccessFile raf = null;try{raf = new RandomAccessFile("hello.txt","rw");raf.seek(3);String str = raf.readLine();//读取出要插入处之后的所有字符// long l = raf.getFilePointer();//获取当前指针的位置// System.out.println(l);//12raf.seek(3);//把指针调到第三个的位置raf.write("123456789".getBytes());//写入要插入的内容raf.write(str.getBytes());//写入原来的后面字符}catch(Exception e) {e.printStackTrace();}finally{if(raf != null){try{raf.close();}catch(Exception e){e.printStackTrace();}}}}
}

IO流练习
在这里插入图片描述

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class test1 {public static void main(String[] args) {   test1 t = new test1();System.out.println("请输入一个字符串:");String str = t.nextString();System.out.println(str);int j = t.nextInt();System.out.println(j + 20);}public String nextString() {InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);String str = null;try {str = br.readLine();}catch(IOException e) {e.printStackTrace();}return str;}public int nextInt() {return Integer.parseInt(nextString());}public boolean nextBoolean() {return Boolean.parseBoolean(nextString());}}

感谢大家的支持,关注,评论,点赞!
参考资料:
尚硅谷宋红康20天搞定Java基础下部

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/71841.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

OpenCV(二十三):中值滤波

1.中值滤波的原理 中值滤波&#xff08;Median Filter&#xff09;是一种常用的非线性图像滤波方法&#xff0c;用于去除图像中的椒盐噪声等离群点。它的原理是基于邻域像素值的排序&#xff0c;并将中间值作为当前像素的新值。 2.中值滤波函数 medianBlur() void cv::medianBl…

怎么把视频转换成mp4格式

怎么把视频转换成mp4格式&#xff1f;如今&#xff0c;随着科技的不断发展&#xff0c;我们在工作中接触到的多媒体视频格式也越来越多。其中&#xff0c;MP4作为一种广泛兼容的视频格式&#xff0c;在许多软件中都能轻松播放&#xff0c;并且成为了剪辑与裁剪视频时大家常用的…

2023年高教社杯数学建模国赛 赛题浅析

2023年国赛如期而至&#xff0c;为了方便大家尽快确定选题&#xff0c;这里将对赛题进行浅析&#xff0c;以分析赛题的主要难点、出题思路以及选择之后可能遇到的难点进行说明&#xff0c;方便大家尽快确定选题。 难度排序 B>A>C 选题人数 C>A>B (预估结果&…

机器学习笔记之最优化理论与方法(三)凸集的简单认识(下)

机器学习笔记之最优化理论与方法——凸集的简单认识[下] 引言回顾&#xff1a;基本定义——凸集关于保持集合凸性的运算仿射变换 凸集基本性质&#xff1a;投影定理点与凸集的分离支撑超平面定理 引言 继续凸集的简单认识(上)进行介绍&#xff0c;本节将介绍凸集的基本性质以及…

go小知识2

Golang开发新手常犯的50个错误_gezhonglei2007的博客-CSDN博客 一些题目整理&#xff0c;附带大佬的解释 1.go中哪些值不能寻址& 常量&#xff08;const常量&#xff0c;字面值3.14&#xff0c;字符串“xxx”&#xff0c;函数或方法, map的val值&#xff09; golang中接…

OpenCV(二十五):边缘检测(一)

目录 1.边缘检测原理 2.Sobel算子边缘检测 3.Scharr算子边缘检测 4.两种算子的生成getDerivKernels() 1.边缘检测原理 其原理是基于图像中灰度值的变化来捕捉图像中的边界和轮廓。梯度则表示了图像中像素强度变化的强弱和方向。 所以沿梯度方向找到有最大梯度值的像素&…

Linux网络编程 网络基础知识

目录 1.网络的历史和协议的分成 2.网络互联促成了TCP/IP协议的产生 3.网络的体系结构 4.TCP/IP协议族体系 5.网络各层的协议解释 6.网络的封包和拆包 7.网络预备知识 1.网络的历史和协议的分成 Internet-"冷战"的产物 1957年十月和十一月&#xff0c;前苏…

C#__线程的优先级和状态控制

线程的优先级&#xff1a; 一个CPU同一时刻只能做一件事情&#xff0c;哪个线程优先级高哪个先运行&#xff0c;优先级相同看调度算法。 在Thread类中的Priority属性&#xff08;Highest,Above,Normal,BelowNormal,Lowest&#xff09;可以影响线程的优先级 关于…

swiper删除虚拟slide问题

在存在缓存的情况下&#xff0c;删除较前的slide&#xff0c;会出现当前slide与后一个slide重复出现的情况 假设当前存在5个slide&#xff0c;且这5个slide已缓存&#xff0c;则删除slide2后&#xff0c;仍为5个slide&#xff0c;且slide2的内容变为slide3的内容&#xff0c;此…

Pushgetway安装和使用

1、Pushgetway安装和使用 1.1 Pushgateway是什么 pushgateway 是另一种数据采集的方式&#xff0c;采用被动推送来获取监控数据的prometheus插件&#xff0c;它可以单独运行在 任何节点上&#xff0c;并不一定要运行在被监控的客户端。 首先通过用户自定义编写的脚本把需要监…

记一次时间序列算法的自回归预测--ARAutoreg

背景 最近公司给客户要做一些数据的预测&#xff0c;但是客户不清楚哪些做起来比较符合他们的&#xff0c;于是在经过与业务方的沟通&#xff0c;瞄准了两个方面的数据 1.工程数据&#xff1a;对工程数据做评估&#xff0c;然后做预警&#xff0c;这个想法是好的&#xff0c;…

DGIOT-Modbus-RTU控制指令05、06的配置与下发

[小 迪 导 读]&#xff1a;伴随工业物联网在实际应用中普及&#xff0c;Modbus-RTU作为行业内的标准化通讯协议。在为物联网起到采集作用的同时&#xff0c;设备的控制也是一个密不可分的环节。 场景解析&#xff1a;在使用Modbus对设备进行采集后&#xff0c;可以通过自动控制…

多波束测线问题

多波束测线问题 问题的背景是海洋测深技术&#xff0c;特别是涉及单波束测深和多波束测深系统。这些系统利用声波传播原理来测量水体深度。 单波束测深系统通过向海底发射声波信号并记录其返回时间来测量水深。该系统的特点是每次只有一个波束打到海底&#xff0c;因此数据分布…

理解项目开发(寺庙小程序)

转载自&#xff1a;历经一年&#xff0c;开发一个寺庙小程序&#xff01; (qq.com) 破防了&#xff01;为方丈开发一款纪念小程序&#xff01; (qq.com) 下面内容转载自&#xff1a;程序员5K为青岛啤酒节开发个点餐系统&#xff01; (qq.com) 看一个人如何完成一个项目的开发…

CSS笔记(黑马程序员pink老师前端)浮动,清除浮动

浮动可以改变标签的默认排列方式。浮动元素常与标准流的父元素搭配使用. 网页布局第一准则:多个块级元素纵向排列找标准流&#xff0c;多个块级元素横向排列找浮动。 float属性用于创建浮动框&#xff0c;将其移动到一边&#xff0c;直到左边缘或右边缘触及包含块或另一个浮动框…

分类预测 | MATLAB实现PCA-LSTM(主成分长短期记忆神经网络)分类预测

分类预测 | MATLAB实现PCA-LSTM(主成分长短期记忆神经网络)分类预测 目录 分类预测 | MATLAB实现PCA-LSTM(主成分长短期记忆神经网络)分类预测预测效果基本介绍程序设计参考资料致谢 预测效果 基本介绍 MATLAB实现PCA-LSTM(主成分长短期记忆神经网络)分类预测。Matlab实现基于P…

【java】【项目实战】[外卖十一]项目优化(Ngnix)

目录 一、Nginx概述 1、Nginx介绍 2、Nginx下载和安装 3、Nginx目录结构 二、Nginx命令 1、查看版本 2、检查配置文件正确性 3、启动和停止 4、重新加载配置文件 三、Nginx配置文件结构 1、全局块 2、events块 3、http块 四、Nginx具体应用 1、部署静态资源 2、…

LeetCode 904. 水果成篮

题目链接 力扣&#xff08;LeetCode&#xff09;官网 - 全球极客挚爱的技术成长平台 题目解析 在你去摘水果的时候&#xff0c;你当前只能拥有两种种类的水果&#xff0c;若想拿第三种水果&#xff0c;就需要发下前两种水果中的一种。 法一&#xff1a;滑动窗口哈希表(未优化…

【Linux】shell脚本和bat脚本:

文章目录 一、脚本对应环境&#xff1a;【1】shell&#xff1a;linux环境&#xff1b;后缀名为.sh【2】bat&#xff1a;windows环境&#xff1b;后缀名为.bat或者.cmd 二、脚本执行&#xff1a;【1】shell执行【2】bat脚本执行 三、脚本相关命令&#xff1a;1. shell命令【1】s…

有向图和无向图的表示方式(邻接矩阵,邻接表)

目录 一.邻接矩阵 1.无向图​编辑 2.有向图 补充&#xff1a;网&#xff08;有权图&#xff09;的邻接矩阵表示法 二.邻接表 1.无向图 2.有向图 三.邻接矩阵与邻接表的关系 一.邻接矩阵 1.无向图 &#xff08;1&#xff09;对角线上是每一个顶点与自身之间的关系&…