Java——Contents1 (File, byte stream)

File class

File class creation function

method name illustrate
public boolean createNewFile() but if a file with that name does not exist, create a new empty file named with that abstract path
public boolean mkdir() Create a directory named by this abstract path
public boolean mkdirs() Create the directory named by this abstract path, including any necessary but non-existing parent directories
import java.io.File;
import java.io.IOException;

/*
File类

public boolean createNewFile()   但具有该名称的文件不存在时,创建一个有该抽象路径命名的新空文件
	如果文件不存在,就创建文件,并返回true
	如果文件存在,就不创建文件,并返回false
 
 
public boolean mkdir()创建由此抽象路径命名的目录
	如果目录不存在,就创建文件,并返回true
	如果目录存在,就不创建文件,并返回false
	
	
public boolean mkdirs()创建由此抽象路径命名的目录,包括任何必须但不存在的父目录
	如果目录不存在,就创建文件,并返回true
	如果目录存在,就不创建文件,并返回false


*/

public class FileDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//需求1:要在E:\\itcast目录下创建一个文件java.txt
		File f1 = new File("E:\\itcast\\java.txt");
		System.out.println(f1.createNewFile());//抛出异常
		System.out.println("---------");

		//需求2:要在E:\\itcast目录下创建一个目录JavaSE
		File f2 = new File("E:\\itcast\\JavaSE");
		System.out.println(f2.mkdir());
		System.out.println("---------");

		//需求3:要在E:\\itcast目录下创建一个多级目录JavaWEB\\HTML
		File f3 = new File("E:\\itcast\\JavaWEB\\HTML");
		System.out.println(f3.mkdirs());
		System.out.println("---------");

		//需求4:要在E:\\itcast目录下创建一个文件javase.txt
		File f4 = new File("E:\\itcast\\javase.txt");
		//		System.out.println(f4.mkdir());//创建了一个javase.txt目录,不能根据路径名决定是文件还是目录
		System.out.println(f4.createNewFile());//会返回false,因为不能存在同名的,不管是文件还是目录

	}
}

File class judgment and acquisition function

method name illustrate
public boolean isDirectory() Tests whether the File denoted by this abstract pathname is a directory
public boolean isFire() Tests whether the File denoted by this abstract pathname is a file
public boolean exists() Tests whether the File denoted by this abstract pathname exists
public String getAbsolutePath() Returns the absolute pathname string for this abstract pathname
public String getPath() converts this abstract pathname to a pathname string
public String getName() Returns the name of the file or directory denoted by this abstract pathname
public String[] list() Returns a string array of the names of the files and directories in the directory denoted by this abstract pathname
public File[] listFiles() Returns an array of File objects for the files and directories in the directory denoted by this abstract pathname
import java.io.File;
import java.io.IOException;

/*
File类判断和获取功能**

public boolean isDirectory() 测试此抽象路径名表示的File是否为目录
public boolean isFire()测试此抽象路径名表示的File是否为文件
public boolean exists()测试此抽象路径名表示的File是否存在

public  String getAbsolutePath()返回此抽象路径名的绝对路径名字符串
public String getPath()将此抽象路径名转换为路径名字符串
public String getName()返回由此抽象路径名表示的文件或目录的名称

public String[] list()返回此抽象路径名表示的目录中的文件和目录的名称字符串数组
public File[] listFiles()返回此抽象路径名表示的目录中的文件和目录的File对象数组

*/

public class FileDemo2 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//创建一个file对象
		File f = new File("java.txt");
		//		System.out.println(f.createNewFile());

		//		public boolean isDirectory() 测试此抽象路径名表示的File是否为目录
		//		public boolean isFire()测试此抽象路径名表示的File是否为文件
		//		public boolean exists()测试此抽象路径名表示的File是否存在
		System.out.println(f.isDirectory());
		System.out.println(f.isFile());
		System.out.println(f.exists());
		/*运行结果:
		false
		true
		true
		*/

		//		public  String getAbsolutePath()返回此抽象路径名的绝对路径名字符串
		//		public String getPath()将此抽象路径名转换为路径名字符串
		//		public String getName()返回由此抽象路径名表示的文件或目录的名称
		System.out.println(f.getAbsolutePath());
		System.out.println(f.getPath());
		System.out.println(f.getName());
		/*运行结果:
		F:\Users\ASUS\eclipse-workspace\hello java\java.txt
		java.txt//封装的路径
		java.txt//路径的名称
		*/

		System.out.println("---------");
		//		public String[] list()返回此抽象路径名表示的目录中的文件和目录的名称字符串数组
		//		public File[] listFiles()返回此抽象路径名表示的目录中的文件和目录的File对象数组
		File f2 = new File("E:itcast");
		String[] strArray = f2.list();
		for (String str : strArray) {
    
    
			System.out.println(str);
		}
		System.out.println("---------");
		File[] fileArray = f2.listFiles();
		for (File file : fileArray) {
    
    
			//			System.out.println(file);
			//			System.out.println(file.getName());
			if (file.isFile()) {
    
    //如果是文件就输出名称
				System.out.println(file.getName());
			}

		}

	}
}

Running result:
insert image description here
File class delete function

method name illustrate
public boolean delete() delete the file or directory denoted by this abstract pathname

The difference between absolute path and relative path

  • Absolute path: a complete path name , which can locate the file it represents without any other information. For example: E:\ \tcast\ \java.txt
  • Relative paths: must be interpreted using information taken from other pathnames. For example: javafile\ \java.txt

Considerations when deleting directories:

  • If a directory has content (directories, files), it cannot be deleted directly . The content of the directory should be deleted first, and the directory can be deleted last
import java.io.File;
import java.io.IOException;

/*
File类删除功能

public boolean delete()   删除由此抽象路径名表示的文件或目录 

*/
public class FileDemo3 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//		File f1=new File("E:\\itcast\\java.txt");
		//需求1:在当前模块目录下创建java.txt文件
		File f1 = new File("java.txt");
		//		System.out.println(f1.createNewFile());

		//		需求2:删除当前模块目录下的java.txt文件
		System.out.println(f1.delete());
		System.out.println("--------");

		//		需求3:在当前模块下创建ifcast目录
		File f2 = new File("itcast");
		//		System.out.println(f2.mkdir());

		//		需求4:删除当前模块下创建ifcast目录
		System.out.println(f2.delete());
		System.out.println("--------");

		//		需求5:在当前模块下创建itcast目录,然后再该目录下创建java.txt文件
		File f3 = new File("itcast");
		//		System.out.println(f3.mkdir());
		File f4 = new File("itcast\\java.txt");
		//若没有上级目录:java.io.IOException: 系统找不到指定的路径。
		//		System.out.println(f4.createNewFile());

		//		需求6:删除当前模块下的目录itcast
		System.out.println(f4.delete());
		System.out.println(f3.delete());//false:如果要删除的目录下面还有内容,就不能直接删

	}
}

recursion

Recursion overview: From a programming point of view, recursion refers to the phenomenon of calling the method itself in the method definition

Recursive problem-solving ideas:
convert a complex problem layer by layer into a smaller-scale problem similar to the original problem to solve.
The recursive strategy can describe the multiple repeated calculations required for the problem-solving process with only a small number of programs.

Recursively solve the problem to find two things:

  • Recursive exit: otherwise memory overflow will occur
  • Recursion Rules: Smaller Problems Similar to the Original Problem
public class DiGuiDemo {
    
    
	public static void main(String[] args) {
    
    
		//回顾不死神兔问题:求第20个月兔子的对数
		//每个月的兔子对数:1,1,2,3,5,8...
		int[] arr = new int[20];

		arr[0] = 1;
		arr[1] = 1;

		for (int i = 2; i < arr.length; i++) {
    
    
			arr[i] = arr[i - 1] + arr[i - 2];

		}
		System.out.println(arr[19]);
		System.out.println(f(20));
	}

	/*
	递归解决问题,首先要定义一个方法
		定义一个方法f(n);表示第n个月的兔子对数
		那么,第n-1个月的兔子对数f(n-1)
		同理,第n-2个月的兔子f(n-2)
		
	//StackOverflowError:当堆栈溢出发生时抛出一个应用程序递归太深
		
		*/
	public static int f(int n) {
    
    
		if (n == 1 || n == 2) {
    
    
			return 1;
		}
		return f(n - 1) + f(n - 2);
	}

}

operation result:
insert image description here

Case: recursively find factorial

Requirement: Use recursion to find the factorial of 5, and output the result on the console

/*
案例:递归求阶乘
需求:用递归求5的阶乘,并把结果在控制台输出
*/
public class DiGuiDemo2 {
    
    
	public static void main(String[] args) {
    
    
		System.out.println("5的阶乘是:" + f(5));
	}

	//定义一个方法,用于递归求阶乘
	public static int f(int n) {
    
    
		if (n == 1) {
    
    
			return 1;
		}

		return n * f(n - 1);
	}
}

operation result:
insert image description here

Case: traversing directories

Requirement: Given a path E:\ \itcast, please traverse all the content in this directory through recursion, and output the absolute paths of all files on the console
insert image description here

import java.io.File;

/*
案例:遍历目录
需求:给定一个路径E:\\itcast,请通过递归完成遍历该目录下的所有内容,
并把所有文件的绝对路径输出在控制台
*/

public class DiGuiDemo3 {
    
    
	public static void main(String[] args) {
    
    
		//根据给定的路径创建对象
		File f = new File("E:\\itcast");

		get(f);
	}

	//定义一个方法。
	public static void get(File f) {
    
    
		//获取给定目录下所有内容
		File[] fileArray = f.listFiles();
		//遍历该file数组,得到每一个file对象
		if (null != fileArray) {
    
    
			for (File file : fileArray) {
    
    
				//判断该file是否是目录
				if (file.isDirectory()) {
    
    
					//是,递归调用
					get(file);
				} else {
    
    
					//不是,获取绝对路径,输出
					System.out.println(file.getAbsolutePath());
				}
			}
		}

	}

}

operation result:
insert image description here

byte stream

IO stream overview and classification

Overview of IO streams:

  • IO: input/output (Input/Output)
  • Stream: It is an abstract concept and a general term for data transmission. That is to say, the transmission of data between devices is called flow, and the essence of flow is data transmission
  • IO flow is used to deal with data transmission between devices.
    Common applications: file copy; file upload; file download

IO flow classification:

  • According to the flow of data input
    stream: read data
    output stream: write data
  • Divided according to data type
    Byte stream: byte input stream; byte output stream
    Character stream: character input stream; character output stream

Generally speaking, the classification of IO streams is based on data types .

  • If the data is opened through the Notepad software that comes with Window, we can still read the content inside , so use the character stream, otherwise use the byte stream. If you don't know which type of stream to use, use byte stream

byte stream write data

Byte stream abstract base class:

  • InputStream: This abstract class is the superclass of all classes that represent byte input streams
  • OutputStream: This abstract column is the superclass of all classes representing byte output streams
  • Features of subclass names: subclass names use their parent name as the suffix of the subclass name

FileOutputStream: The file output stream is used to write data to File

  • FileOutputStream(String name): Create a file output stream to write to the file with the specified name

Steps to write data using byte output stream:

  • Create a byte output stream object (call the system function to create a file, create a byte output stream object, and let the byte output stream object point to the file)
  • Call the write data method of the byte output stream object
  • free resources (closes this file output stream and frees any system resources associated with this stream)
import java.io.FileOutputStream;
import java.io.IOException;

/*

字节流写数据**

字节流抽象基类:

 - InputStream:这个抽象类是表示字节输入流的所有类的超类
 - OutputStream:这个抽象列是表示字节输出流的所有类的超类
 - 子类名特点:子类名称都是以其父名作为子类名的后缀

FileOutputStream:文件输出流用与将数据写入File

 - FileOutputStream(String name):创建文件输出流以指定的名称写入文件
*/

public class FileOutputStreamDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//创建字节输出流对象
		//FileOutputStream(String name):创建文件输出流以指定的名称写入文件
		FileOutputStream fos = new FileOutputStream("..\\hello java\\fos.txt");
		/*
		做了三件事:
			调用系统功能创建了文件
			创建了字符输出流对象
			让字符输出流对象指向创建好的文件
		*/

		//void write (int b):将指定的字节写入此文件输出流
		fos.write(97);//a
		//		fos.write(57);//9
		//		fos.write(55);//7

		//最后都要释放资源
		//void close():关闭此文件输出流并释放与此流相关联的任何系统资源
		fos.close();

	}
}

Three ways of byte stream input

3 ways to write data in byte stream

method name illustrate
void write(int b) Writes the specified bytes to this file output stream, one byte at a time
void write(byte[] b) Writes b.lelength bytes from the specified byte array to this file output stream, one byte array data at a time
void write(byte[] b,int off,int len) Write len bytes from the specified byte array to this file output stream starting from offset off, and write part of the data one byte array at a time
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*

构造方法:
	FileOutputStream(String name):创建文件输出以指定的名称写入文件
	FileOutputStream(File file):创建文件输出流以写入有指定的File对象表示的文件


字节流写数据的3种方法

void write(int b)   将指定的字节写入此文件输出流,
					一次写一个字节数据
void write(byte[] b)将b.leangth字节从指定的字节数组写入此文件输出流,
					一次写一个字节数组数据
void write(byte[] b,int off,int len)将len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流,
									一次写一个字节数组的部分数据
*/

public class FileOutputStreamDemo2 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//1:FileOutputStream(String name):创建文件输出以指定的名称写入文件
		FileOutputStream fos = new FileOutputStream("..\\hello java\\fos.txt");
		//new File(name)
		//		FileOutputStream fos=new FileOutputStream(new File("..\\hello java\\fos.txt"));//相当于上面的

		//2:FileOutputStream(File file):创建文件输出流以写入有指定的File对象表示的文件
		//		File file=new File("..\\hello java\\fos.txt");
		//		FileOutputStream fos2=new FileOutputStream(file);
		//		FileOutputStream fos2=new FileOutputStream(new File("..\\hello java\\fos.txt"));//两种都可以

		//void write(int b)   将指定的字节写入此文件输出流,
		//一次写一个字节数据
		//		fos.write(97);
		//		fos.write(98);
		//		fos.write(99);
		//		fos.write(100);
		//		fos.write(101);
		/*abcde*/

		//void write(byte[] b)将b.leangth字节从指定的字节数组写入此文件输出流,
		//一次写一个字节数组数据
		//		byte[] bys= {97,98,99,100,101};
		//byte[] getByted():返回字符串对应的字节数组
		byte[] bys = "abcde".getBytes();
		//		fos.write(bys);
		/*abcde*/

		//void write(byte[] b,int off,int len)将len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流,
		//一次写一个字节数组的部分数据
		//		fos.write(bys,0,bys.length);//abcde
		fos.write(bys, 1, 3);//bcd

		//释放资源
		fos.close();

	}
}

Two small problems in writing data by byte stream
How to implement line break when writing data by byte stream?

  • After writing the data, add a newline character
  • window:\r\n
  • linux:\n
  • mac:\r

How does byte stream write data implement additional writing?

  • public FileOutputStream(String name,boolean append)
  • Create a file output stream to write to a file with the specified name. If the second parameter is true, the bytes will be written to the end of the file instead of the beginning
import java.io.FileOutputStream;
import java.io.IOException;

/*
字节流写数据的两个小问题

	1.字节流写数据如何实现换行?
	不同系统换行识别是不一样的
		windeow:\r\n
		linux:\n
		mac:\r
		
	2.字节流写数据如何实现追加写入?
		public fileOutputStream(String name,boolean append)
			创建文件输出流以指定的名称写入文件。
			如果第二个参数为true,则字节将写入文件的末尾而不是开头
*/

public class FileOutputStreamDemo3 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//创建字节输出流对象
		//		FileOutputStream fos=new FileOutputStream("..\\hello java\\fos.txt");
		FileOutputStream fos = new FileOutputStream("..\\hello java\\fos.txt", true);

		//写数据
		for (int i = 0; i < 10; i++) {
    
    
			fos.write("hello".getBytes());
			fos.write("\r\n".getBytes());//换行
		}

		//释放资源
		fos.close();

	}
}

Byte stream write data added exception handling

finally : A finally block is provided to perform all clear operations during exception handling. For example, the release of resources in the IO stream
features: the statement controlled by finally will be executed unless the JVM exits

try{
	可能出现异常的代码;
}catch(异常类名 变量名){
	异常的处理代码;
}finally{
	执行所有清楚操作;
}
import java.io.FileOutputStream;
import java.io.IOException;

/*
字节流数据加入异常处理
*/
public class FileOutputStreamDemo4 {
    
    
	public static void main(String[] args) {
    
    
		/*
		try {
			FileOutputStream fos = new FileOutputStream("..\\hello java\\fos.txt");
			fos.write("hello".getBytes());
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		*/
		
		//加入finally来实现释放资源
		FileOutputStream fos = null;//在外面创建fos,给初始化null
		try {
    
    
			//			fos=new FileOutputStream("Z:\\hello java\\fos.txt");//错误地址
			fos = new FileOutputStream("..\\hello java\\fos.txt");
			fos.write("hello".getBytes());
			fos.close();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			if (null != fos) {
    
    //释放资源前对fos进行不为null的判断
				try {
    
    
					fos.close();//快捷键try...catch方法
				} catch (IOException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
}

Byte stream read data (read data one byte at a time)

Requirement: Read the content in the file fos.txt and output it on the console

FileInputStream: Gets input bytes from a file in the file system

  • FileInputStream(String name): Creates a FileInputStream by opening a connection to the actual file named by the pathname name in the file system

Steps to read data using byte input stream:

  1. Create a byte input stream object
  2. Call the read data method of the byte input stream object
  3. release resources
import java.io.FileInputStream;
import java.io.IOException;

/*
字节流读数据(一次读一个字节数据)**

需求:把文件fos.txt中的内容读取出来在控制台输出

FileInputStream:从文件系统中的文件获取输入字节

 - FileInputStream(String name):通过打开与实际文件的连接俩创建一个FileInputStream,该文件由文件系统中的路径名name命名

使用字节输入流读数据的步骤:

 1. 创建字节输入流对象
 2. 调用字节输入流对象的读数据方法
 3. 释放资源
*/

public class FileInputStreamDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//创建字节输入流对象
		//FileInputStream(String name)
		FileInputStream fis = new FileInputStream("..\\hello java\\fos.txt");
		/*
			fos.txt中的内容
				ab
		*/

		//调用字节输入流对象的读数据方法
		//int read():从该输入流读取一个字节的数据

		/*
		//第一次读取数据
		int i = fis.read();
		System.out.println(i);//97
		System.out.println((char)i);//a 强制转换
		
		//第一次读取数据
		i = fis.read();
		System.out.println(i);//98
		System.out.println((char)i);//b 强制转换
		
		//再多读取两次
		i = fis.read();
		System.out.println(i);//-1 文件中没有数据了,返回-1
		i = fis.read();
		System.out.println(i);//-1
		*/

		/*
		//判断条件:文件末尾-1
		int by=fis.read();
		while(by!=-1) {
		//			System.out.println(by);
			System.out.print((char)by);
			by=fis.read();
		}
		运行结果:
		ab
		
		*/

		//优化上面的程序
		int by;
		/*
		fis.read():读数据
		by=fis.read():把读取到的数据赋值给by
		by!=-1:判断读取到的数据是否是-1
		
		*/
		while ((by = fis.read()) != -1) {
    
    
			System.out.print((char) by);
		}
		//		运行结果:
		//		ab

		//释放资源
		fis.close();

	}
}

Case: copy text file

Requirement: Copy "E:\\itcast\\window.txt" to "window.txt" in the module directory

Analysis: Copying a text file means reading the content of the file from one file ( data source ) and writing it to another file ( destination )

Data source: E:\\itcast\\window.txt—read data—InputStream—FileInputStream
destination: ...\\hello java\\window.txt—write data—OutputStream—FileOutputStream

insert image description here

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
案例:复制文本文件
需求:把“E:\\\itcast\\\窗里窗外.txt”复制到模块目录下的“窗里窗外.txt”

分析:复制文本文件,就是把文件内容从一个文件中读取出来(**数据源**),然后写入另一个文件中(**目的地**)

数据源:E:\\\itcast\\\窗里窗外.txt---读数据---InputStream---FileInputStream
目的地:..\\\hello java\\\窗里窗外.txt---写数据---OutputStream---FileOutputStream

*/
public class CopyDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//根据数据源创建字节输入流对象
		FileInputStream fis = new FileInputStream("E:\\itcast\\窗里窗外.txt");

		//根据目的地创建字节输出流对象
		FileOutputStream fos = new FileOutputStream("..\\hello java\\窗里窗外.txt");

		//读写数据,复制文本文件(一次读取一个字节,一次写入一个字节)
		int by;
		while ((by = fis.read()) != -1) {
    
    
			fos.write(by);
		}

		//释放资源
		fos.close();
		fis.close();

	}
}

Running result:
insert image description here
byte stream read data (read one byte array data at a time)

Requirement: Read the content in the file fos.txt and output it on the console

Steps to read data using byte input stream:

  1. Create a byte input stream object
  2. Call the read data method of the byte input stream object
  3. release resources

insert image description here

import java.io.FileInputStream;
import java.io.IOException;

/*
字节流读数据(一次读一个字节数组数据)**

需求:把文件fos.txt中的内容读取出来在控制台输出

使用字节输入流读数据的步骤:

 1. 创建字节输入流对象
 2. 调用字节输入流对象的读数据方法
 3. 释放资源
*/
public class FileInputStreamDemo2 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//创建字节输入流对象
		FileInputStream fis = new FileInputStream("..\\hello java\\fos.txt");

		//调用字节输入流对象的读数据方法
		//int read(byte[] b):从该输入流读取最多 b.length个字节的数据到一个字节数组

		/*
		byte[] bys=new byte[5];
		
		//第一次读取数据
		int len = fis.read(bys);
		System.out.println(len);
		//String(byte[] bytes)
		//		System.out.println( new String(bys) );
		System.out.println( new String(bys,0,len) );
		
		//第二次读取数据
		len = fis.read(bys);
		System.out.println(len);
		//		System.out.println( new String(bys) );
		System.out.println( new String(bys,0,len) );
		
		//第三次读取数据
		len = fis.read(bys);
		System.out.println(len);
		//String(byte[] bytes,int offset,int length)
		System.out.println( new String(bys,0,len) );
		//		System.out.println( new String(bys) );
		
		//再多读取两次
		len = fis.read(bys);
		System.out.println(len);
		len = fis.read(bys);
		System.out.println(len);
		
		运行结果:
		5
		hello
		5
		
		wor
		5
		ld 
		
		-1
		-1
		
		
		*/

		/*
		hello\r\n
		world\r\n
		
		第一次:hello
		第二次:\r\nwor
		第三次:ld\r\nr
		*/

		byte[] bys = new byte[1024];//1024及其整数倍
		int len;
		while ((len = fis.read(bys)) != -1) {
    
    
			System.out.print(new String(bys, 0, len));
		}
		/*
		运行结果:
		hello
		world 
		
		*/

		//释放资源
		fis.close();

	}
}

Case: copying pictures

Requirement: Copy "E:\\itcast\\mn.jpg" to "mn.jpg" in the module directory
insert image description here

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
案例:复制图片

需求:把“E:\\\itcast\\\mn.jpg”复制到模块目录下的“mn.jpg”

*/
public class CopyJpg {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//根据数据源创建字节输入流对象
		FileInputStream fis = new FileInputStream("E:\\itcast\\mn.jpg");

		//根据目的地创建字节输出流对象
		FileOutputStream fos = new FileOutputStream("..\\hello java\\mn.jpg");

		//读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
		byte[] bys = new byte[1024];
		int len;
		while ((len = fis.read(bys)) != -1) {
    
    
			fos.write(bys, 0, len);
		}

		//释放资源
		fis.close();
		fos.close();

	}
}

Running result:
insert image description here
byte buffer stream

byte buffered stream:

  • BufferOutputStream: This class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without incurring a call to the underlying system for each byte written.
  • BufferedInputStream: Creating a BufferedInputStream will create an internal buffer array. When reading or skipping bytes from the stream, the internal buffer will be refilled as needed from the contained input stream, many bytes at a time

Construction method:

  • Byte buffered output stream: BufferedOutputStream(OutputStream out)
  • Byte buffered input stream: BufferedInputStream(InputStream in)

Why does the construction method need a byte stream instead of a specific file or path?

  • The byte buffer stream only provides a buffer , and the real read and write data has to rely on the basic byte stream object to operate
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
字节缓冲流:

 - BufferOutputStream:该类实现缓冲输出流。通过设置这样的输出流,应用程序可以想底层输出流写入字节,而不必为写入的每个字节导致底层系统的调用
 - BufferedInputStream:创建BufferedInputStream将创建一个内部缓冲区数组。当从流中读取或跳过字节时,内部缓冲区将根据需要从所包含的输入流中重新填充,一次很多字节

构造方法:

 - 字节缓冲输出流:BufferedOutputStream(OutputStream out)
 - 字节缓冲输入流:BufferedInputStream(InputStream in)

*/
public class BufferStreamDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//字节缓冲输出流:BufferedOutputStream(OutputStream out)
		//		FileOutputStream fos=new FileOutputStream("..\\hello java\\bos.txt");
		//		BufferedOutputStream bos=new BufferedOutputStream(fos);

		//合并成一步
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("..\\hello java\\bos.txt"));
		//写数据
		bos.write("hello\r\n".getBytes());
		bos.write("world\r\n".getBytes());
		//释放资源
		bos.close();

		//字节缓冲输入流:BufferedInputStream(InputStream in)
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("..\\hello java\\bos.txt"));

		//读数据
		/*
		//一次读取一个字节数据
		int by;
		while((by=bis.read())!=-1) {
			System.out.print((char)by);
		}
		*/
		//一次读取一个字节数组的数据
		byte[] bys = new byte[1024];
		int len;
		while ((len = bis.read(bys)) != -1) {
    
    
			System.out.print(new String(bys, 0, len));
		}

		//释放资源
		bis.close();

	}
}

operation result:
insert image description here
insert image description here

Case: copy video

Requirement: Copy "E:\\itcast\\Byte Stream Copy Picture.avi" to "Byte Stream Copy Picture.avi" in the module directory
Idea:

  1. Create a byte input stream object from a data source
  2. Create a byte output stream object based on the destination
  3. Read and write data, copy video
  4. release resources

insert image description here

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
案例:复制视频
需求:把“E:\\\itcast\\\字节流复制图片.avi”复制到模块目录下的“字节流复制图片.avi”
思路:

 1. 根据数据源创建字节输入流对象
 2. 根据目的地创建字节输出流对象
 3. 读写数据,复制视频
 4. 释放资源
 
 
 四种方式实现复制视频,并记录每种方式复制视频的时间
 	1.基本字节流一次读写一个字节		共耗时:72743毫秒
 	2.基本字节流一次读写一个字节数组		共耗时:87毫秒
 	3.字节缓冲流一次读写一个字节		共耗时:198毫秒
 	4.字节缓冲流一次读写一个字节数组		共耗时:22毫秒

*/

public class CopyAviDemo {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//记录开始时间
		long startTime = System.currentTimeMillis();

		//复制视频
		//		method1();
		//		method2();
		//		method3();
		method4();

		//记录结束时间
		long endTime = System.currentTimeMillis();
		System.out.println("共耗时:" + (endTime - startTime) + "毫秒");

	}

	//4.字节缓冲流一次读写一个字节数组
	private static void method4() throws IOException {
    
    
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\字节流复制图片.avi"));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("..\\hello java\\字节流复制图片.avi"));

		byte[] bys = new byte[1024];
		int len;
		while ((len = bis.read(bys)) != -1) {
    
    
			bos.write(bys, 0, len);
		}

		bis.close();
		bos.close();

	}

	//3.字节缓冲流一次读写一个字节
	private static void method3() throws IOException {
    
    
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\字节流复制图片.avi"));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("..\\hello java\\字节流复制图片.avi"));

		int by;
		while ((by = bis.read()) != -1) {
    
    
			bos.write(by);
		}

		bis.close();
		bos.close();

	}

	//2.基本字节流一次读写一个字节数组
	private static void method2() throws IOException {
    
    
		FileInputStream fis = new FileInputStream("E:\\itcast\\字节流复制图片.avi");
		FileOutputStream fos = new FileOutputStream("..\\hello java\\字节流复制图片.avi");

		byte[] bys = new byte[1024];
		int len;
		while ((len = fis.read(bys)) != -1) {
    
    
			fos.write(bys, 0, len);
		}

		fis.close();
		fos.close();

	}

	//1.基本字节流一次读写一个字节
	private static void method1() throws IOException {
    
    
		//E:\\\itcast\\\字节流复制图片.avi
		//模块目录下的字节流复制图片.avi
		FileInputStream fis = new FileInputStream("E:\\itcast\\字节流复制图片.avi");
		FileOutputStream fos = new FileOutputStream("..\\hello java\\字节流复制图片.avi");

		int by;
		while ((by = fis.read()) != -1) {
    
    
			fos.write(by);

		}

		fos.close();
		fis.close();
	}
}

Guess you like

Origin blog.csdn.net/weixin_47678894/article/details/119527430