17.文件和流
17.1 File文件
Java中的对文件的管理,通过java.io包中的File类实现
Java中文件的管理,主要是针对文件或是目录路径名的管理 文件的属性信息 文件的检查 文件的删除等 不包括文件的访问
java
package com.neusoft.io;
import java.io.File;
import java.io.IOException;
import java.net.URI;
/**
* 项目: javaadvice
* 类名: MyFile
* 创建时间: 2020/11/23 8:44
* 描述 : 文件的操作
* 作者 : 张金山
* QQ : 314649444
* Site: https://jshand.gitee.io
*/
public class MyFile {
public static void main(String[] args) {
//通过构造器创建对象
// File file = new File("d:\\");
System.out.println("系统分隔符\t"+File.separator);
System.out.println("系统分隔符\t"+File.separatorChar);
//代表D盘,File代表,目录或者是文件
File dirD = new File("d:/");
File filesD = new File("d:/files");
//文件句柄
File txta = new File("d:/a.txt");
File txtb = new File("d:/","b.txt");
URI uri = URI.create("file:///D:/");
File txtc = new File(uri);
File txtd = new File(filesD.getPath(),"d.txt"); // d:/files/d.txt
//判断文件句柄是否存在
System.out.println("dirD.exists():"+dirD.exists());
System.out.println("txta.exists():"+txta.exists());
//判断file句柄是目录还是文件
System.out.println("dirD.isDirectory():\t"+dirD.isDirectory()); //true
System.out.println("txta.isDirectory():\t"+txta.isDirectory()); // ?
System.out.println("txta.isFile():\t"+txta.isFile()); // ?
//文件的创建
try {
boolean createFile = txta.createNewFile();
//获取file路径
// System.out.println("txta.getPath()\t"+txta.getPath());
// System.out.println("txta.getAbsolutePath()\t"+txta.getAbsolutePath());
System.out.println(txta.getAbsolutePath()+",创建\t"+createFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
boolean createFile = txtd.createNewFile(); // 如果文件目录不存在,java.io.IOException: 系统找不到指定的路径。
System.out.println(txtd.getAbsolutePath()+",创建\t"+createFile);
} catch (IOException e) {
e.printStackTrace();
}
//创建目录
File dirs = new File("d:/java1/d1123");
// boolean mkdir = dirs.mkdir(); //只能创建一级目录
boolean mkdirs = dirs.mkdirs(); // 创建多级目录
System.out.println("dirs create:\t"+mkdirs);
//其他的方法
try {
//创建临时文件
File tmpFile = File.createTempFile("new",".txt");
System.out.println("tmpFile.getPath()\t"+tmpFile.getPath());
File tmpFile2 = File.createTempFile("new",".txt",new File("D:/"));
System.out.println("tmpFile2.getPath()\t"+tmpFile2.getPath());
System.out.println("tmpFile2.delete()\t"+tmpFile2.delete());
System.out.println("new File(\"d:/qqq.txt\").delete()\t"+new File("d:/qqq.txt").delete());
// tmpFile2.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("txta.canRead()\t"+txta.canRead());
System.out.println("txta.canWrite()\t"+txta.canWrite());
System.out.println("txta.canExecute()\t"+txta.canExecute());
//list列目录
String[] children = new File("D:\\stf\\styy").list();
for (String child : children) {
// System.out.println(child);//文件名列表
}
File[] stfFiles = new File("D:\\stf\\styy").listFiles();
for (File stfFile : stfFiles) {
// System.out.printf("name:%s,大小%d\r\n",stfFile.getName(),stfFile.length());
}
boolean renameToSuccess = txta.renameTo(new File("D:/rename.txt"));
System.out.println("renameToSuccess\t"+renameToSuccess);
}
}
17.2 流的概念
- 流的分类
- 按流的方向不同
- 输入流、输出流
- 按处理数据的单位不同
- 字节流、字符流
- 按功能不同
- 节点流、处理流
- 按流的方向不同
- Java语言中,控制数据流的类都放在java.io包中
- java.io包中有两大继承体系
- 以byte处理为主的Stream类,他们的命名方式是XXXStream
- 以字符处理为主的Reader / Writer类,他们的命名方式XXXReader或XXXWriter
- InputStream、OutputStream、Reader、Writer这四个类,是这两大继承体系的父类
17.2 InputStream
此抽象类是表示输入字节流的所有类的超类 InputStream常用的方法
方法 | 含义 |
---|---|
int read( ) | 一次读取一个byte的数据,并以int类型把数据返回来,如果没有数据可以读了,会返回”-1” |
int read(byte[] buffer) | 把所读取到的数据放在这个byte数组中,返回一个int型的数据,这个int型数据存储了返回的真正读取到的数据byte数 |
int read(byte[] buffer,int offset,int length) | 读取length个字节,并存储到一个字节数组buffer中,并从offset位置开始返回实际读取的字节数 |
void close( ) | 关闭此输入流并释放与该流关联的所有系统资源 |
java
package com.neusoft.io;
import java.io.*;
/**
* 项目: javaadvice
* 类名: MyInputStream
* 创建时间: 2020/11/23 10:57
* 描述 :
* 作者 : 张金山
* QQ : 314649444
* Site: https://jshand.gitee.io
*/
public class MyInputStream {
public static void main(String[] args) {
File file = new File("D:/a.txt");
InputStream is = null;
try {
is =new FileInputStream(file);
// for (int i = 0; i <3 ; i++) {
// int bt = is.read(); //
// System.out.println((char)bt);
// }
byte[] bt = new byte[10];
int len = -1;
while( (len = is.read(bt)) != -1){
for (byte b : bt) {
System.out.println("char:\t"+(char)b);
}
}
// while( (len = is.read(bt,4,6)) != -1){
// for (byte b : bt) {
// System.out.println("char:\t"+(char)b);
// }
// }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
17.3 输出流 OutputStream
此抽象类是表示输出字节流的所有类的超类 OutputStream常用的方法
方法 | 含义 |
---|---|
void write(byte[] buffer) | 将要输出的数组先放在一个byte数组中,然后用这个方法一次把一组数据输出出去 |
void write(byte[] buffer,int off,int len) | 将指定字节数组中从偏移量 off 开始的 len 个字节写入此输出流 |
abstract void write(int b) | 将指定的字节写入此输出流 |
void close( ) | 关闭此输出流并释放与此流有关的所有系统资源 |
void flush( ) | 刷新此输出流并强制写出所有缓冲的输出字节 |
java
package com.neusoft.io;
import java.io.*;
/**
* 项目: javaadvice
* 类名: MyInputStream
* 创建时间: 2020/11/23 10:57
* 描述 :
* 作者 : 张金山
* QQ : 314649444
* Site: https://jshand.gitee.io
*/
public class MyOutputStream {
public static void main(String[] args) {
String msg = "hello world ! ";
File file = new File("D:/out.txt");
OutputStream os = null;
try {
boolean append = true;
os = new FileOutputStream(file,append);
byte[] bts = msg.getBytes();
// for (byte bt : bts) {
// os.write(bt);
// }
// os.write(bts); //将字节数组全量输出
os.write(bts,0,5); //指定从字节数组的off位置开始输出,输出len个字节
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
17.4 练习
定义一个方法,传入两个参数srcFile、destFile 实现将src复制到dest
java
package com.neusoft.io;
import java.io.*;
/**
* 项目: javaadvice
* 类名: FileUtils
* 创建时间: 2020/11/23 11:48
* 描述 :
* 作者 : 张金山
* QQ : 314649444
* Site: https://jshand.gitee.io
*/
public class FileUtils {
/**
*
* @param srcFile
* @param destFile
* @return 成功与否
*/
public static boolean copy(String srcFile ,String destFile){
return copy(new File(srcFile),new File(destFile));
}
public static boolean copy(File srcFile , File destFile){
InputStream is = null;
OutputStream os = null;
// try(is = new FileInputStream(null)){
//
// }
try{
is = new FileInputStream(srcFile);
os = new FileOutputStream(destFile);
byte[] bts = new byte[1024];
int len = -1;
while ( (len = is.read(bts)) != -1){
os.write(bts,0,len);
}
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public static void main(String[] args) {
boolean success = FileUtils.copy("D:/a.txt","d:/dest.txt");
System.out.println("copy :\t"+success);
}
}
17.5 Reader
用于输入字符流的抽象类
17.5.1 常用方法
方法 | 含义 |
---|---|
int read( ) | 一次读取一个char的数据,并以int类型把数据返回来,如果没有数据可以读了,会返回”-1” |
int read(char[] cbuffer) | 把所读取到的数据放在这个char数组中,返回一个int型的数据,这个int型数据存储了返回的真正读取到的数据char数 |
int read(char[] cbuffer,int offset,int length) | 读取length个字符,并存储到一个字节数组cbuffer中,并从offset位置开始返回实际读取的字符数 |
void close( ) | 关闭此Reader并释放与其关联的所有系统资源 |
java
package com.neusoft.io;
import java.io.*;
/**
* 项目: javaadvice
* 类名: MyReader
* 创建时间: 2020/11/23 14:41
* 描述 :
* 作者 : 张金山
* QQ : 314649444
* Site: https://jshand.gitee.io
*/
public class MyReader {
public static void main(String[] args) {
File file = new File("D:/a.txt");
Reader reader = null;
try {
reader = new FileReader(file);
// for (int i = 0; i < 20; i++) {
// System.out.println((char)reader.read());
// }
char[] chars = new char[3];
int len = -1;
while( (len = reader.read(chars,0,2)) != -1){
System.out.println(new String(chars,0,2));
}
// while( (len = reader.read(chars)) != -1){
// System.out.println(new String(chars));
// }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
17.6 Writer
java
package com.neusoft.io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* 项目: javaadvice
* 类名: MyWriter
* 创建时间: 2020/11/23 15:30
* 描述 :
* 作者 : 张金山
* QQ : 314649444
* Site: https://jshand.gitee.io
*/
public class MyWriter {
public static void main(String[] args) {
File file = new File("D:/out.txt");
Writer writer = null;
try {
boolean append = true;
writer = new FileWriter(file,append);
// writer.write('E');
// writer.write(new char[]{'a','b','c'});
writer.write("中文222.....");
writer.flush(); //清空缓冲区
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer!= null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
17.8 对象的序列号
java
package com.neusoft.io;
import java.io.Serializable;
/**
* 项目: javaadvice
* 类名: Student
* 创建时间: 2020/11/23 16:19
* 描述 :
* 作者 : 张金山
* QQ : 314649444
* Site: https://jshand.gitee.io
*/
public class Student implements Serializable {
private String name;
private Integer age;
private transient String password;
//6447444974629283018L
private static final long serialVersionUID = 1;
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public Student(String name, Integer age, String password) {
this.name = name;
this.age = age;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", password='" + password + '\'' +
'}';
}
}
java
package com.neusoft.io;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 项目: javaadvice
* 类名: ObjectReadAndWrite
* 创建时间: 2020/11/23 16:20
* 描述 :
* 作者 : 张金山
* QQ : 314649444
* Site: https://jshand.gitee.io
*/
public class ObjectReadAndWrite {
public static void write() {
Student stu = new Student("张飞",50,"123456");
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream(new File("d:/stu.obj"));
//将对象写入到硬盘,
oos = new ObjectOutputStream(fos);
oos.writeObject(stu);
oos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void read() {
FileInputStream fis = null;
try {
fis = new FileInputStream(new File("d:/stu.obj"));
//将对象写入到硬盘,
ObjectInputStream ois = new ObjectInputStream(fis);
Student obj = (Student)ois.readObject();
// System.out.println("getName\t"+obj.getName());
// System.out.println("getAge\t"+obj.getAge());
System.out.println(obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
write();
read();
}
}
