B站视频指路:尚硅谷Java入门视频教程(在线答疑+Java面试真题)_哔哩哔哩_bilibili
写在前面:马上秋招,打算从0开始再学一遍Java,开个知识点记录贴,就当做课堂笔记吧.
Java IO原理
·I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输.如读写文件,网络通讯等
·Java程序中 对于数据的输入/输出操作以"流(stream)"的方式进行
·java.io包下提供了各种"流"类和接口 用以获取不同种类的数据 并通过标准的方法输入或者输出数据
流的分类
·按操作数据单位不同分为:字节流(8 bit)、字符流(16 bit)
·按数据流的流向的不同分为:输入流 输出流
·按流的角色的不同分为:节点流 处理流
1.Java的IO流工涉及40多个类 实际上非常规则 都是从以上四个抽象基类派生的
2.由这四个类派生出来的子类的名称都是以其父类名作为子类名后缀
访问文件:节点流
其他的(访问文件下面的):处理流
*流的体系结构
tips:开发中一般不用节点流 因为 效率太差 一般考虑用缓冲流
抽象基类 | 节点流(或文件流) | 缓冲流(处理流的一种) |
---|---|---|
InputStraem | FileInputStraemFileReader (read(Byte [ ] cbuf)) | BufferedInputStraem (read(Byte [ ] cbuf)) |
OutputStream | FileOutputStream (write(Byte [ ] cbuf,0,len)) | BufferedOutputStream (write(Byte [ ] cbuf,0,len)) flush()刷新缓冲区 |
Reader | FileReader (read(char [ ] cbuf)) | BufferedReader (read(char [ ] cbuf) or (readLine()) |
Writer | FileWriter (write(char [ ] cbuf,0,len)) | BufferedWriter (write(char [ ] cbuf,0,len)) flush()刷新缓冲区 |
练习1:把txt文件内容读入程序中 并输出到控制台
tips:①read():返回读入的一个字符 若达到文件末尾 返回-1
②异常的处理:为了保证流资源一定可以执行关闭操作 需使用t-c-f处理异常
③读入的文件一定要存在 不然就会报FileNotFoundException
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderWriterTest {
// public static void main(String[] args) {
// File file = new File("hello.txt");//相对于当前的priject
// //D:\IdeaProjects\reviewoop\hello.txt
// System.out.println(file.getAbsoluteFile());
// File file1 = new File("src/hello.txt");//相对于当前的priject
// System.out.println(file1.getAbsoluteFile());
// //D:\IdeaProjects\reviewoop\src\hello.txt
// }
/*
将src下的hello.txt文件内容读入程序中 并输出到控制台
*/
@Test
public void test() {
FileReader fileReader = null;
try {
//1.实例化File类文件 指明要操作的文件
File file = new File("hello.txt");//相对于当前的Module
//2.提供具体的流
fileReader = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符 若达到文件末尾 返回-1
//方式1:
int read = fileReader.read();
while(read!=-1){
System.out.print((char) read);
read=fileReader.read();
}
//方式2:语法上针对方式1的修改
int read2 = fileReader.read();
while((read2=fileReader.read())!=-1){
System.out.print((char) read2);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流的关闭操作
try {
if(fileReader!=null)
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
练习1:把txt文件内容读入程序中 并输出到控制台 使用read(char[]cbuf)
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderWriterTest2 {
@Test
public void test() {
FileReader fileReader = null;
try {
//对read()操作升级:使用read的重载方法
//1.实例化File类文件 指明要操作的文件
File file = new File("hello.txt");//相对于当前的Module
//2.提供具体的流
fileReader = new FileReader(file);
//3.数据的读入
//read(char []cbuf):返回每次读入cbuf数组中的字符的个数
//若达到文件末尾 返回-1
char[] cbuf = new char[5];
int len;
while((len=fileReader.read(cbuf))!=-1){
// 方式1:
//错误的写法 会出现 helloWorld123ld
// for(int i=0;i<cbuf.length;i++){
// System.out.print(cbuf[i]);
// }
//正确的:
for(int i=0;i<len;i++){
System.out.print(cbuf[i]);
}
//方式2:
//错误的写法 会出现 helloWorld123ld
// String str = new String(cbuf);
// System.out.println(str);
//正确的:
String str = new String(cbuf,0,len);
System.out.print(str);
}
fileReader.read(cbuf);
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源的关闭
try {
if(fileReader!=null)
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
练习2:从内存中写出数据到硬盘的文件里
·输出操作 对应的File可以不存在 若不存在 在输出的过程中 会自动创建此文件
·若存在:若使用的是FileWriter(file,false)/FileWriter(file):对原有文件的覆盖
若使用的是FileWriter(file,true):不会对原有的文件进行覆盖 而是在原有文件基础上追加内容
import org.junit.Test;
import java.io.*;
public class SAD {
@Test
public void test() {
FileWriter fileWriter = null;
try {
//1.提供File类的对象 指明写出到的文件
File file = new File("hello1.txt");//相对于当前的Module
//2.提供FileWriter的对象 用于 数据的写出
fileWriter = new FileWriter(file);
//3.写出的操作
fileWriter.write("zhangke\n");
fileWriter.write("zhangke1\n");
fileWriter.write("zhangke2");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileWriter!=null)
//流资源的关闭
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
练习3:实现文本文件的复制
import org.junit.Test;
import java.io.*;
public class FileReaderWriterTest2 {
@Test
public void test() {
FileReader fr = null;
FileWriter fw = null;
try {
//1.创建File类的对象 指明读入和写出的文件
File srcFile = new File("hello.txt");
File destFile = new File("hello2.txt");
//2.创建输入流和输出流的对象
fr = new FileReader(srcFile);
fw = new FileWriter(destFile,true);
//3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;//记录每次读入到cbuf数组中字符的个数
while ((len=fr.read(cbuf))!=-1){
//每次写出len个字符
fw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭流资源
try {
if(fw!=null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fr!=null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//不能使用字符流(FileWriter和FileReader)来处理图片等字节数据 要用字节流
读取文本文件最好用字符流 不要 用字节流FileInputStream(可能会出现乱码)
即: 针对在控制台输出 不在内存层面读
①对于文本文件(.txt, .java, .c, .app),使用字符流处理
②对于非文本文件(.jpg, .avi, .mp4, .doc, .ppt......),使用字节流处理
如果是复制的话 文本文件也可以用字节流
例题:使用FileInputStream和FileOutputStream复制非文本文件
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileIOputStreamTest {
@Test
public void test() {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
//1.造文件
File srcfile = new File("zk.jpg");
File destfile = new File("zk2.jpg");
//2.造流
inputStream = new FileInputStream(srcfile);
outputStream = new FileOutputStream(destfile);
//3.复制的过程
byte[] buffer = new byte[5];
int len;//记录每次读取字节的个数
while((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream!=null)
//4.关闭资源
{
try {
if(inputStream!=null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(outputStream!=null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
例题:使用FileInputStream和FileOutputStream复制非文本文件的测试类
public void copy(String srcPath,String destPath) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
//1.造文件
File srcfile = new File(srcPath);
File destfile = new File(destPath);
//2.造流
inputStream = new FileInputStream(srcfile);
outputStream = new FileOutputStream(destfile);
//3.复制的过程
byte[] buffer = new byte[1024];
int len;//记录每次读取字节的个数
while((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream!=null)
//4.关闭资源
{
try {
if(inputStream!=null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(outputStream!=null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void testCopyFile(){
long l = System.currentTimeMillis();
copy("zk.jpg","zhangke.jpg");
long l2 = System.currentTimeMillis();
System.out.println(l2 - l);
}
处理流之一:缓冲流的使用
1.缓冲流
·BufferedInputStraem
·BufferedOutputStream
·BufferedReader
·BufferedWriter
2.作用:提高流的读取、写入的速度
原因:内部提供了一个缓冲区
3.处理流,就是"套接"在已有的流(不一定是节点流)的基础上
例题:非文本文件的复制 ·BufferedInputStraem和·BufferedOutputStream的使用
import org.junit.Test;
import java.io.*;
public class BufferedTest {
/*
实现非文本文件的赋值
*/
@Test
public void test(){
BufferedInputStream bi = null;
BufferedOutputStream oi = null;
try {
//1.造文件
File srcFile = new File("zk.jpg");
File destFile = new File("zkdfsdfdsf.jpg");
//2.造流
//2.1造节点流
FileInputStream ifis = new FileInputStream(srcFile);
FileOutputStream ofis = new FileOutputStream(destFile);
//2.2造缓冲流
bi = new BufferedInputStream(ifis);
oi = new BufferedOutputStream(ofis);
//3.复制的细节 读取 写入
byte[]buffer = new byte[10];
int len;
while ((len=bi.read(buffer))!=-1){
oi.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//先关外层的流 再关内层的流
try {
if(bi!=null)
bi.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(oi!=null)
oi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// //说明:在关闭外层流的同时 内层也会自动的关闭 所以 可以省略内层流的关闭
// ifis.close();
// ofis.close();
}
}
缓冲流与节点流读写速度对比
与上面的使用FileInputStream和FileOutputStream复制非文本文件的测试类做对比
public void cop(String srcPath,String destPath){
BufferedInputStream bi = null;
BufferedOutputStream oi = null;
try {
//1.造文件
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2.造流
//2.1造节点流
FileInputStream ifis = new FileInputStream(srcFile);
FileOutputStream ofis = new FileOutputStream(destFile);
//2.2造缓冲流
bi = new BufferedInputStream(ifis);
oi = new BufferedOutputStream(ofis);
//3.复制的细节 读取 写入
byte[]buffer = new byte[1024];
int len;
while ((len=bi.read(buffer))!=-1){
oi.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//先关外层的流 再关内层的流
try {
if(bi!=null)
bi.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(oi!=null)
oi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void teee(){
long start = System.currentTimeMillis();
String src = "C:\\Users\\13604\\Desktop\\kk.mp4";
String dest = "C:\\Users\\13604\\Desktop\\k2.mp4";
cop(src,dest);
long end = System.currentTimeMillis();
System.out.println(end - start);
}
很明显速度提高了
tips: .flush()//刷新缓冲区
例题:文本文件的复制 ·BufferedReader和·BufferedWriter的使用
BufferedReader写入文件有两种方法
import org.junit.Test;
import java.io.*;
public class BufWnRTest {
@Test
public void test() {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
//1.造文件&造流
bufferedReader = new BufferedReader(new FileReader("hello.txt"));
bufferedWriter = new BufferedWriter(new FileWriter("hello222.txt"));
//2.复制的具体操作
//方式1:使用char[]
// int len;
// char [] cbuf = new char[10];
// while((len=bufferedReader.read(cbuf))!=-1){
// bufferedWriter.write(cbuf,0,len);
// }
//方式2:使用String
String data;
while ((data = bufferedReader.readLine())!=null){
// 法1: bufferedWriter.write(data+"\n");//data中不包含换行符
//法2:
bufferedWriter.write(data);
bufferedWriter.newLine();//提供换行的操作
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.关闭资源
try {
if(bufferedReader!=null)
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bufferedWriter!=null)
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
练习:
1.分别使用节点流:FileInputStream、FileOutputStream和缓冲流:BufferedInputStream、BufferedOutputStream实现文本文件/图片/视频文件的复制 并比较二者在数据复制方面的效率
ans:如上文所示
2.实现图片的加密操作
tips:两次^就恢复到了原来的数据
import org.junit.Test;
import java.io.*;
public class password {
@Test
//图片的加密
public void test() {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
// File fis = new File("zk.jpg");
// File fos = new File("jiami.jpg");
// fileInputStream = new FileInputStream(fis);
// fileOutputStream = new FileOutputStream(fos);
fileInputStream = new FileInputStream("zk.jpg");
fileOutputStream = new FileOutputStream("jiami.jpg");
int len;
byte[] buff = new byte[1024];
while((len=fileInputStream.read(buff))!=-1){
//字节数组进行修改 下面是错误写法 增强型for 取出来的数据是赋给新的变量了 buff本身是不变的
// for(byte b : buff){
// b= (byte) (b^5);
// }
//正确的
for (int i = 0; i < len; i++) {
buff[i] = (byte) (buff[i]^5);
}
fileOutputStream.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileInputStream!=null)
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fileOutputStream!=null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
//图片的解密
public void test2() {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
File fis = new File("jiami.jpg");
File fos = new File("jiemi.jpg");
fileInputStream = new FileInputStream(fis);
fileOutputStream = new FileOutputStream(fos);
int len;
byte[] buff = new byte[1024];
while((len=fileInputStream.read(buff))!=-1){
//字节数组进行修改 下面是错误写法 增强型for 取出来的数据是赋给新的变量了 buff本身是不变的
// for(byte b : buff){
// b= (byte) (b^5);
// }
//正确的
for (int i = 0; i < len; i++) {
buff[i] = (byte) (buff[i]^5);
}
fileOutputStream.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileInputStream!=null)
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fileOutputStream!=null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.获取文本上每个字符出现的次数
提示:遍历文本的每一个字符;字符及出现的次数保存在Map中;将Map中数据写入文件
也可以用FileWriter 但是BufferedWriter有.newLine() 所有用BufferedWriter好一点
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class zifu {
@Test
public void test() {
FileReader fileReader = null;
BufferedWriter fileWriter = null;
try {
fileReader = new FileReader("hello.txt");
fileWriter = new BufferedWriter(new FileWriter("ans131.txt"));
int c = 0;
Map<Character,Integer> map = new HashMap<Character, Integer>();
while((c=fileReader.read())!=-1){
int count = map.getOrDefault((char)c,0)+1;
map.put((char)c,count);
}
Set<Map.Entry<Character,Integer>> entrySet = map.entrySet();
for (Map.Entry<Character,Integer> entry : entrySet) {
switch (entry.getKey()){
case ' ':
fileWriter.write("空格:"+entry.getValue());
break;
case '\t':
fileWriter.write("tab:"+entry.getValue());
break;
case '\r':
fileWriter.write("enter:"+entry.getValue());
break;
case '\n':
fileWriter.write("换行:"+entry.getValue());
break;
default:
fileWriter.write(entry.getKey()+":"+entry.getValue());
break;
}
fileWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileWriter!=null)
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fileReader!=null)
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
处理流之二:转换流的使用
·转换流提供了再字节流和字符流之间的转换
·Java API提供了两个转换流(都属于字符流)
①InputStreamReader:将InputStream转换为Reader
即:将一个字节的输入流转换为字符的输入流
②OutputStreamWriter:将Writer转换为OutputStream
即:将一个字符的输出流转换为字节的输出流
·字节流中的数据都是字符时,转成字符流操作更高效
·很多时候我们使用转换流来处理文件乱码问题.实现编码和解码的功能
即:
解码:字节、字节数组--->字符数组、字符串
编码:字符数组、字符串--->字节、字节数组
·字符集
解码:字节、字节数组--->字符数组、字符串: 在控制台输出 InputStreamReader
package asdf;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class zhuanhuanliu {
@Test
public void test() {
FileInputStream fis = null;
InputStreamReader ist = null;//使用系统默认的字符集
try {
fis = new FileInputStream("hello.txt");
ist = new InputStreamReader(fis);
InputStreamReader ist2 = new InputStreamReader(fis, StandardCharsets.UTF_8);//使用UTF-8
//具体使用哪个字符集 取决于"hello.txt"保存时使用的字符集
char[] cbuf = new char[20];
int len;
while((len=ist.read(cbuf))!=-1){
String s = new String(cbuf,0,len);
System.out.print(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(ist!=null)
ist.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fis!=null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
解码:字节、字节数组--->字符数组、字符串 && 编码:字符数组、字符串--->字节、字节数组
综合使用:InputStreamReader&OutputStreamReader
package asdf;
import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class heiheihei {
@Test
public void test(){
InputStreamReader inputStreamReader = null;
OutputStreamWriter outputStreamWriter = null;
try {
File file1 = new File("hello.txt");
File file2 = new File("hello_GBK.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
inputStreamReader = new InputStreamReader(fis, StandardCharsets.UTF_8);
outputStreamWriter = new OutputStreamWriter(fos,"gbk");
char[] cbuf = new char[20];
int len;
while((len=inputStreamReader.read(cbuf))!=-1){
outputStreamWriter.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(inputStreamReader!=null)
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
字符集
标准的输入、输出流(了解) 是字节流
·System.in和System.out分别代表了系统标准的输入和输出设备
·默认输入设备是:键盘 ,输出设备是:显示器
·System.in的类型是InputStream
·System.out的类型是PrintStream,其是OutputStream的子类 FilterOutputStream的子类
·重定向:通过System类的setIn、setOut方法对默认设备进行改变
·public static void setIn(InputStream in)
·public static void setOut(PrintStream out)
练习:从键盘输入字符串 要求将读取到的整行字符串转成大写输出 然后继续进行输入操作 直至当输入"e"或者"exit"时,退出程序
tips:使用System.in实现 System.in(字节流)-->转换流-->BufferedReader(字符流)的readLine()
package asdf;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class OtherStreamTest {
public static void main(String[] args) {
BufferedReader bufferedReader = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
bufferedReader = new BufferedReader(isr);
while (true){
String data = bufferedReader.readLine();
if("e".equalsIgnoreCase(data)||"exit".equalsIgnoreCase(data)){
break;
}
String upperCase = data.toUpperCase();
System.out.println(upperCase);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(bufferedReader!=null)
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
代码:
package asdf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MyInput {
public static String readString() {
BufferedReader bufferedReader = null;
String str = "";
try {
InputStreamReader isr = new InputStreamReader(System.in);
bufferedReader = new BufferedReader(isr);
str = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static int readInt(){
return Integer.parseInt(readString());
}
public static double readDouble(){
return Double.parseDouble(readString());
}public static byte readByte(){
return Byte.parseByte(readString());
}
public static short readShort(){
return Short.parseShort(readString());
}
public static long readLong(){
return Long.parseLong(readString());
}
public static void main(String[] args) {
System.out.println(MyInput.readString());
}
}
打印流(了解):
练习:
package asdf;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class AFBJSDFG {
@Test
public void test(){
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream("hASDASD.txt");
//创建打印输出流 设置为自动刷新模式(写入换行或字节'\n'时都会刷新输出缓冲区)
ps = new PrintStream(fos,true);
if(ps!=null){
//把标准输出流(控制台输出)改成文件
System.setOut(ps);
}
for (int i = 0; i < 256; i++) {
System.out.print((char)i);
if(i%50==0){
System.out.println();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if(ps!=null)
ps.close();
}
}
}
数据流(了解)
练习:将内存中的字符串、基本数据类型的变量写出到文件中
tips:处理异常仍然使用t-c-f
package asdf;
import org.junit.Test;
import java.io.*;
public class sdfd {
@Test
public void test() throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("he.txt"));
dos.writeUTF("asdfhsdjkfgh");
dos.flush();//刷新操作 将内存中的数据写入文件
dos.writeInt(12);
dos.flush();
dos.writeBoolean(true);
dos.flush();
dos.close();
}
/*
将文件中存储的基本数据类型变量和字符串读取到内存中 保存在变量中
*/
@Test
public void tes2t() throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream("he.txt"));
String s = dis.readUTF();//读取顺序不能变 要与当初保存数据的顺序一致
System.out.println(s);
int i = dis.readInt();
System.out.println(i);
boolean b = dis.readBoolean();
System.out.println(b);
dis.close();
}
}
练习:
1.说明流的三种分类方式
①流向:输入 输出
②数据单位:字节流 字符流
③流的角色:节点流 处理流
2.写出4个IO流中的抽象基类 4个文件流 4个缓冲流
3.字节流与字符流的区别与使用情境
字节流:处理非文本文件 read(byte[ ] buffer) / read()
字符流:处理文本文件 read(char[ ] cbuf) / read()
4.使用缓冲流实现a.jpg文件复制为b.jpg文件的操作
package asdf;
import org.junit.Test;
import java.io.*;
public class wer {
@Test
public void test() throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("hello.txt"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("h42.txt"));
byte [] buff = new byte[1024];
int len;
while ((len=bufferedInputStream.read(buff))!=-1){
bufferedOutputStream.write(buff,0,len);
}
bufferedInputStream.close();
bufferedOutputStream.close();
}
}
5.转换流是哪两个类 分别的作用是什么 请分别创建两个类对象
InputStreamReader:将输入的字节流转换为输入的字符流
OutputStreamWriter:将输出的字符流转换为输出的字节流
输入输出流的标准化过程
1.输入过程:
①创建File类对象 指明读取的数据来源(要求此文件一定存在)
②创建相应的输入流,将File类的对象作为参数 传入流的构造器中
③具体的读入过程:
创建相应的byte[ ] 或 char[ ]
④关闭流资源
tips:程序中出现的异常需要使用t-r-f处理
2.输出过程:
①创建File类对象 指明写出的数据位置(不要求此文件一定存在)
②创建相应的输出流,将File类的对象作为参数 传入流的构造器中
③具体的写出过程:
write(byte[ ] / char[ ] buffer , 0 , len)
④关闭流资源
tips:程序中出现的异常需要使用t-r-f处理
对象流
ObjectInputStream和ObjectOutputStream
用于存储和读取基本数据类型数据或对象的处理流.它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来
·序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
·反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
ObjectInputStream和ObjectOutputStream不能序列化static和transient修饰的成员变量
·为了方便地操作Java语言的基本数据类型和String的数据 可以使用数据流
·数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
DataInputStream和DataOutputStream
分别"套装"在InputStream和OutputStream子类的流上
·DataInputStream中的方法
·DataOutputStream中的方法
将上述的方法的read改为相应的write即可
对象的序列化
·对象序列化机制允许把内存中的java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点.当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
·序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据使其在保存和传输时可被还原
·序列化是RMI(Remote Method Invoke-远程方法调用) 过程的参数和返回值都必须实现的机制,而RMI是JaveEE的基础.因此序列化机制是JavaEE平台的基础
·如果需要让某个对象支持序列化机制,则必须让对象所属的类及属性时可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一.否则 会抛出NotSerialzableException异常
①Serializable ②Externalizable
例题: 对象流序列化和反序列化 字符串操作
package oopstreamhah;
import org.junit.Test;
import java.io.*;
public class ObjectInOutputTest {
//序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
@Test
public void test() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("zhangke.dat"));
oos.writeObject(new String("账款回款圣诞节回复看"));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(oos!=null)
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//反序列化过程:将磁盘文件中的对象还原为内存中的一个java对象
@Test
public void test2() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("zhangke.dat"));
Object obj = ois.readObject();
String s = (String) obj;
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if(ois!=null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
例题: 自定义类Person实现对象流序列化和反序列化
Personl需要满足如下的要求 方可序列化
①需要实现接口 Serializable(这个接口没有任何抽象方法)
②当前类提供一个全局常量:serialVersionUID
③除了当前类Person类需要实现Serializable接口之外,还必须保证其内部所有属性也
必须是可序列化的.(默认情况下基本数据类型都是可序列化的)
比如成员变量有一个自定义类Account 那么Account也需要是可序列化的
tips:ObjectInputStream和ObjectOutputStream不能序列化static和transient修饰的成员变量
package oopstreamhah;
import java.io.Serializable;
/*
Personl需要满足如下的要求 方可序列化
①需要实现接口 Serializable
②当前类提供一个全局常量:serialVersionUID
*/
public class Person implements Serializable {
public static final long serialVersionUID = 234231241221134L;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package oopstreamhah;
import org.junit.Test;
import java.io.*;
public class ObjectInOutputTest {
//序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
@Test
public void test() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("zhangke.dat"));
oos.writeObject(new String("账款回款圣诞节回复看"));
oos.flush();
oos.writeObject(new Person("张柯",18));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(oos!=null)
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//反序列化过程:将磁盘文件中的对象还原为内存中的一个java对象
@Test
public void test2() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("zhangke.dat"));
Object obj1 = ois.readObject();
Object obj2 = ois.readObject();
String s = (String) obj1;
Person p = (Person) obj2;
System.out.println(p.toString());
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if(ois!=null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
serialVersionUID的理解
·凡是实现Serializable接口的类都有一个标识序列化版本标识符的静态变量:
①public static final long serialVersionUID
②serialVersionUID用来表明类的不同版本间的兼容性.简言之 其目的是以序列化对象
进行版本控制,有关各版本反序列化时是否兼容
③如果类没有显式定义这个静态常量 它的值是Java运行时环境根据类内部细节自动生
成的.若类的实例变量做了修改,serialVersionUID可能发生变化.故建议,显式声明
·简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的.在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的
serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本
不一致的异常(InvalidCastException)
RandomAccessFile类
·RandomAccessFile声明在java.io包下 但直接继承与java.lang.Object类 并且它实现了
DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写
·RandomAccessFile类支持"随机访问"的方式,程序可以直接跳到文件的任意地方来读、写
文件 且
①支持只访问文件的部分内容
②可以向已存在的文件后追加内容
·RandomAccessFile对象包含一个记录指针,用以标示当前读写处的位置
RandomAccessFile类对象可以自由移动记录指针
①long getFilePointer():获取文件记录指针的当前位置
②void seek(long pos):将文件记录指针定位到pos位置
练习:复制一张图片
package oopstreamhah;
import org.junit.Test;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
@Test
public void test() {
RandomAccessFile randomAccessFile1 = null;
RandomAccessFile randomAccessFile2 = null;
try {
randomAccessFile1 = new RandomAccessFile("报名照片.jpg","r");
randomAccessFile2 = new RandomAccessFile("报名照片222.jpg","rw");
byte [] buf = new byte[1024];
int len;
while((len=randomAccessFile1.read(buf))!=-1){
randomAccessFile2.write(buf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(randomAccessFile1!=null)
randomAccessFile1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(randomAccessFile2!=null)
randomAccessFile2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
练习:对文件内容进行覆盖
使用RandomAccessFile作为输出流时,写出到的文件若不存在,则在执行过程中自动创建
若写出到的文件存在,则会对原有文件进行覆盖.(默认情况下 从头覆盖)
package oopstreamhah;
import org.junit.Test;
import java.io.IOException;
import java.io.RandomAccessFile;
public class sdgfsdg {
@Test
public void test() {
RandomAccessFile randomAccessFile1 = null;
try {
randomAccessFile1 = new RandomAccessFile("hello.txt","rw");
randomAccessFile1.write("zhangke".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(randomAccessFile1!=null)
randomAccessFile1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
练习:在文件内容指定的地方覆盖字符串(void seek() 默认是0 所以从头覆盖)
package oopstreamhah;
import org.junit.Test;
import java.io.IOException;
import java.io.RandomAccessFile;
public class sdgfsdg {
@Test
public void test() {
RandomAccessFile randomAccessFile1 = null;
try {
randomAccessFile1 = new RandomAccessFile("hello.txt","rw");
randomAccessFile1.seek(3);//将指针调到角标为3的位置
randomAccessFile1.write("zhangke".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(randomAccessFile1!=null)
randomAccessFile1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
练习:在文件内容指定的地方插入字符串 (使用RandomAccessFile实现)
package oopstreamhah;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class sdgfsdg {
@Test
public void test() {
RandomAccessFile randomAccessFile1 = null;
try {
randomAccessFile1 = new RandomAccessFile("hello.txt","rw");
randomAccessFile1.seek(3);//将指针调到角标为3的位置
byte [] buf = new byte[20];
int len;
//保存指针3后面的所有数据到sb当中
StringBuilder sb = new StringBuilder((int) new File("hello.txt").length());
while((len=randomAccessFile1.read(buf))!=-1){
sb.append((new String(buf,0,len)));
}
//此时指针自动跑到了最后 所以还需要再调整到3
randomAccessFile1.seek(3);//将指针调到角标为3的位置
randomAccessFile1.write("tjw".getBytes());
randomAccessFile1.write(sb.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(randomAccessFile1!=null)
randomAccessFile1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
多线程断点下载
NIO.2中Path、Paths、Files类的使用(简单介绍)
1.谈谈你对对象序列化机制的理解
对象序列化机制允许把内存中的java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点.当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
·序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
·反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
2.对象要想实现序列化需要满足哪几个条件
①实现接口:Serializable 标识接口
②对象所在的类提供常量:版本序列号
public static final long serialVersionUID = 234231241221134L;
③要求对象的属性也必须是可序列化的(基本数据类型和String天然就是可序列化的)