文章目录
File类的理解使用
File类的理解
1.File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹);
2.File类声明在java.io包下
3.File类中涉及到关于文件或文件目录的创建,删除、重命名、修改时间、文件大小等方法
未涉及到写入或读取文件,如需要读取和写入文件内容,必须使用IO流来完成
4.后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的“终点”
File类的实例化
1.常用的构造器(构造方法)
File(String filePath)
File(String parentPath,String childPath)
File(File parentFile,String childPath)
public void test(){
//构造器一
File file1=new File("Hello world.txt");//相当于当前Module
File file2=new File("D:\\workspace_idea1\\.idea\\java\\ho.txt");
System.out.println(file1);
System.out.println(file2);
//构造器二
File file3=new File("workspace_idea1","java");
System.out.println(file3);
//构造器三
File file4=new File(file3,"hec.txt");
System.out.println(file4);
}
2.路径的分类
相对路径:相较于某个路径下,指明的路径。
绝对路径:包含盘符在内的文件或文件目录的路径
说明:
IDEA中:
如果使用JUnit中的单元测试方法测试,相对路径即为当前Module下。
如果使用main()测试,相对路径即为当前的Project下。
Eclipse中:
不管使用单元测试方法还是使用main()测试,相对路径都是当前的Project下。
3.路径分隔符
windows和DOS 系统默认使用“\”来表示
UNIX和URL 使用“/”来表示
File类的常用方法
@Test
//对于文件
public void test1(){
File file1=new File("hello.txt");
File file2=new File("D:\\Io\\he.txt");
System.out.println(file1.getAbsoluteFile());//获取绝对路径
System.out.println(file1.getPath());//获取当前文件路径
System.out.println(file1.getName());//获取文件名称
System.out.println(file1.getParent());//获取上一级目录路径。若无,返回null
System.out.println(file1.length());//获取文件长度(即字节数)不能获取目录的长度
System.out.println(new Date(file1.lastModified()));//获取最后一次修改文件时间 毫秒数
}
@Test
//对于文件目录
public void test2(){
File file1=new File("D:\\workspace-idea\\JavaSenior");
String [] list=file1.list();//获取指定文件夹下所有文件或文件目录的名称数组
/*
for(数据类型 变量名 :遍历的目标){//数据类型 变量名:声明一个变量用来接收遍历目标遍历后的元素}
*/
for(String s: list) {//增强for循环
System.out.println(s);
}
File [] l=file1.listFiles();//获取指定文件夹下所有文件或文件目录的File数组
for(File p: l){
System.out.println(p);
}
}
@Test
public void test3(){
File file1=new File("hello.txt");
File file2=new File("D:\\Io\\lo.txt");
boolean b = file2.renameTo(file1);//把文件重命名为指定的文件路径
System.out.println(b);
//返回为true ;file1存在,file2不存在
}
@Test
public void test4(){
File file1=new File("hello.txt");
System.out.println(file1.isDirectory());//判断是否是文件目录
System.out.println(file1.isFile());//判断是否是文件
System.out.println(file1.exists());//判断是否存在
System.out.println(file1.canRead());//判断是否可读
System.out.println(file1.canWrite());//判断是否可写
System.out.println(file1.isHidden());//判断文件是否隐藏
}
@Test
public void test6() throws IOException {
File file1=new File("hi.txt");
//文件的创建与删除
//创建文件,若文件存在则不创建,返回为false;
if(!file1.exists()){
file1.createNewFile();
System.out.println("创建成功1");
}else{
file1.delete();//删除文件或文件夹
System.out.println("删除成功;");
//说明:java中的删除不走回收站。
//要删除一个文件目录,则该文件目录内不能包含文件或文件目录
}
}
@Test
public void test5(){
File file1=new File("D:\\Io\\txt\\1p");
//文件目录的创建
//注:如果你创建文件或文件目录没有写盘符路径。那么,默认在项目路径下
boolean mkdir = file1.mkdir();//若此文件目录的上层目录不存在,则不创建,若文件目录已存在,也不创建
if(mkdir){
System.out.println("创建成功!");
}
boolean mkdirs = file1.mkdirs();//若上层目录不存在,则一并创建;若文件目录存在则不创建
if(mkdirs){
System.out.println("创建成功2");
}
}
}
IO流的理解运用
IO流概述
一.流的分类
1.操作数据单位:字节流、字符流
2.数据的流向:输入流、输出流
3.流的角色:节点流、处理流
图示:
二.流的体系结构
三.输入输出的标准化过程
1.输入过程:
① 创建File类的对象,指明读取的数据的来源。(要求此文件一定要存在)
② 创建相应的输入流,将File类的对象作为参数,传入流的构造器中
③ 具体的读入过程:
创建相应的byte[] 或 char[]。
④ 关闭流资源
说明:程序中出现的异常需要使用try-catch-finally处理。
2.输出过程
① 创建File类的对象,指明写出的数据的位置。(不要求此文件一定要存在)
② 创建相应的输出流,将File类的对象作为参数,传入流的构造器中
③ 具体的写出过程:
write(char[]/byte[] buffer,0,len)
④ 关闭流资源
说明:程序中出现的异常需要使用try-catch-finally处理。
节点流的使用(或文件流)
FileReader的使用
public void textFileReader() {
FileReader reader = null;
try { //异常处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally处理
//读入的文件一定要存在,否则会报错FileNotFoundException。
//1.实例化File对象,指明要操作的文件
File fr = new File("hello.txt");
//2.提供具体的流
reader = new FileReader(fr);
//3.数据的读入
//read():返回读入一个字符,如果达到文件末尾,返回-1
int date;
while ((date = reader.read()) != -1) {
System.out.print((char) date);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流的关闭操作 必须
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
//对read()操作升级:使用read的重载方法
public void testFileReader1() {
FileReader fileReader = null;
try {
//1.实例化File类
File file = new File("hello.txt");
//2.FileReader流的实例化
fileReader = new FileReader(file);
//3.读入操作
//read(char [] cbuf):返回每次读入cbuf数组中的字符的个数,达到文件末尾,返回-1;
char[] t=new char[5];
int read;
while( (read = fileReader.read(t))!=-1){
//方式一:
//错误的写法
// for(int i=0;i<t.length;i++){
// System.out.print(t[i]);
// }
//正确的写法
// for(int i=0;i<read;i++){
// System.out.print(t[i]);
// }
//方式二
//错误写法:等同于方式一
// String str=new String(t);
// System.out.print(str );
//正确写法:
String s = new String(t,0, read);
System.out.print(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader!=null){
//4.资源的关闭
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileWriter的使用
从内存中写出数据到硬盘
1.输出操作,指定的File不存在,也不会报错
2.File对应的硬盘中的文件如果不存在,在程序执行过程中,会自动创建;
File对应的硬盘中的文件如果存在:
若使用的构造器是 FileWriter(file,false) /FileWriter(file) ,会覆盖原有的文件
若使用的构造器是 FileWriter(file,true),不会覆盖原有的文件 ,会在原有的文件下追加内容
*/
@Test
public void testFireWriter() {
//1.实例化File类,指明写出的文件
FileWriter fileWriter = null;
try {
File file = new File("he.txt");
//2.提供具体的写出流
fileWriter = new FileWriter(file,true);
//3.写入操作
fileWriter.write("I need a girlfriends!\n");
fileWriter.write("yes,you need!");
} catch (IOException e) {
e.printStackTrace();
} finally {
}
//4.资源的关闭
if(fileWriter!=null){
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
综合使用
@Test
public void testFileReaderWriter() {
FileReader reader = null;
FileWriter writer = null;
try {
//1.实例化File类,指明读入和写出的文件
File file = new File("hello.txt");
File file1 = new File("ho.txt");
//2.创建输入流和输出流的对象
reader = new FileReader(file);
writer = new FileWriter(file1);
//3.读入,写出操作
int date;
char[] s=new char[10];
while((date=reader.read(s))!=-1){
writer.write(s,0,date);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源的关闭
try {
if(reader!=null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(writer!=null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileInputStream和FileOutputStream的使用(字节流)
总结:对于文本文件(.txt、.java、.c、.cpp)使用字符流
对于非文本文件(.jpg/.mp3/.mp4/.avi/.ppt/.doc等)使用字节流
构造器:
FileInputStream(String name)//可直接写文件目录
FileInputStream(File file) //File 文件
实现对图片的复制:
public void inputOutputStreamTest() {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
//1.实例化File类指明写入写出文件
File file = new File("total.jpg");
File file1 = new File("total1.jpg");
//2.创建写出,读入的流的对象
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file1);
//3.复制过程操作
byte[] bytes = new byte[5];
int len;
while((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
System.out.println("复制成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
if(inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
缓存流的使用
1.缓冲流涉及到的类:
- BufferedInputStream
- BufferedOutputStream
- BufferedReader
- BufferedWriter
2.作用:
作用:提供流的读取、写入的速度
提高读写速度的原因:内部提供了一个缓冲区。默认情况下是8kb
说明: * 资源的关闭:内层流随外层流的关闭而关闭
代码实例:
//BufferInputStream/BufferOutputStream 处理非文本文件
public void testBufferInputOutputStream(){
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
//1.造流
inputStream = new BufferedInputStream(new FileInputStream(new File("qq.jpg")));
outputStream = new BufferedOutputStream(new FileOutputStream(new File("qq1.jpg")));
//2.读取数据
byte[] bytes = new byte[5];
int len;
while((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.关闭资源
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//BufferedReader/ BufferedWriter处理文本文件
@Test
public void test2(){
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader("he.txt"));
writer = new BufferedWriter(new FileWriter("he1.txt"));
//方式一:使用char[]数组
// char[] p=new char[5];
// int len;
// while((len=reader.read(p))!=-1){
// writer.write(p,0,len);
// }
//方式二 :使用String
String str;
while((str=reader.readLine())!=null){
// writer.write(str);//不包含换行
//方法一
// writer.write(str+"\n");
//方法二
writer.write(str);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader!=null){//避免出现空指针异常
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(writer!=null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
转换流的使用
1.转换流涉及到的类:属于字符流
InputStreamReader:将一个字节的输入流转换为字符的输入流
解码:字节、字节数组 —>字符数组、字符串
OutputStreamWriter:将一个字符的输出流转换为字节的输出流
编码:字符数组、字符串 —> 字节、字节数组
说明:编码决定了解码的方式
2.作用:提供字节流与字符流之间的转换
图示:
补充 :字符集;了解就可
1.常见的编码表
ASCII:美国标准信息交换码。
用一个字节的7位可以表示。
ISO8859-1:拉丁码表。欧洲码表
用一个字节的8位表示。
GB2312:中国的中文编码表。最多两个字节编码所有字符
GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
Unicode:国际标准码,融合了目前人类使用的所字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
2.对后面学习的启示
客户端/浏览器端 <----> 后台(java,GO,Python,Node.js,php) <----> 数据库
要求前前后后使用的字符集都要统一:UTF-8.
典型代码
public void testInputStreamReader() throws FileNotFoundException {
InputStreamReader streamReader = null;
try {
FileInputStream inputStream = new FileInputStream("he.txt");
//参数字符集的选择,取决于he.txt文件保存时所用的字符集
//若没有字符集的参数,则使用的是系统默认的字符集
streamReader = new InputStreamReader(inputStream,"utf-8");
char[] le=new char[30];
int len;
while((len=streamReader.read(le))!=-1){
String s = new String(le,0,len);
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(streamReader!=null) {
try {
streamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//综合使用
//转换流的综合使用
编码转换
@Test
public void testInputOutputStreamReaderWriter(){
//1.造文件,造流
InputStreamReader streamReader = null;
OutputStreamWriter streamWriter = null;
try {
File file = new File("he.txt");
File file1 = new File("he_gbk.txt");
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream outputStream = new FileOutputStream(file1);
streamReader = new InputStreamReader(inputStream,"utf-8");
streamWriter = new OutputStreamWriter(outputStream,"gbk");
//2.读入写出操作
char[] p=new char[20];
int len;
while ((len=streamReader.read(p))!=-1){
streamWriter.write(p,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.资源关闭
if(streamReader!=null){
try {
streamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(streamWriter!=null){
try {
streamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
其他流的使用
标准的输入输出流
System.in:标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出
修改默认的输入和输出行为:
System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出的流。
例题:
从键盘输入字符串,读入的整行字符串转为大写后输出,若输入‘e’或exit退出
System.in—>转换流–>BufferedReader
*/
public static void main(String[] args) {
BufferedReader reader = null;
try {
//转换流
InputStreamReader fileReader = new InputStreamReader(System.in);//从键盘读取数据
reader = new BufferedReader(fileReader);
while (true) {
System.out.println("请输入字符串:");
String str = reader.readLine();//读取一整行
if ("e".equalsIgnoreCase(str) || "exit".equalsIgnoreCase(str)) {//忽略大小写判断
System.out.println("程序结束!");
break;
}
String s = str.toUpperCase();//转换大写的方法
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印流
PrintStream 和PrintWriter
说明:
提供了一系列重载的print()和println()方法,用于多种数据类型的输出
System.out返回的是PrintStream的实例
public void test1() {
FileOutputStream outputStream = null;
try {//创建输出流,指定写出文件
outputStream = new FileOutputStream("D:\\Io\\char.txt");
//创建打印输出流,设置为自动刷新模式(写入换行符或'\n'都刷新输出缓存区)
PrintStream printStream = new PrintStream(outputStream, true);
if (printStream != null) {//把标准输出流(控制台输出)改为输出到文件
System.setOut(printStream);
}
for (int i = 0; i <= 255; i++) {
System.out.print((char) i);
if (i % 50 == 0) {
System.out.println();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
数据流
DataInputStream 和 DataOutputStream
作用:
用于读取或写出基本数据类型的变量或字符串
示例代码
//将内存中的字符串、基本数据类型的变量写出到文件中。
public void test2() {
DataOutputStream outputStream = null;
try {
outputStream = new DataOutputStream(new FileOutputStream("data.txt"));
outputStream.writeUTF("刘晨");
outputStream.flush();
outputStream.writeInt(23);
outputStream.flush();
outputStream.writeBoolean(true);
outputStream.flush();//刷新操作,将内存中的数据写入文件
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
public void test3(){
DataInputStream inputStream = null;
try {
inputStream = new DataInputStream(new FileInputStream("data.txt"));
String s=inputStream.readUTF();//与之前写出的一致
int i = inputStream.readInt();
boolean b = inputStream.readBoolean();
System.out.println("姓名:"+s);
System.out.println("年龄:"+i);
System.out.println("是否:"+b);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
对象流
1.对象流:
ObjectInputStream 和 ObjectOutputStream
2.作用:
ObjectOutputStream:内存中的对象—>存储中的文件、通过网络传输出去:序列化过程
ObjectInputStream:存储中的文件、通过网络接收过来 —>内存中的对象:反序列化过程
3.对象的序列化机制:
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘
上,或通过网络将这种二进制流传输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原来的
Java对象
序列化操作
//序列化:将存在的对象输出到磁盘或网络中
public void testObjectOutputStream(){
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream("object.data"));
os.writeObject(new String("不食人间烟火!"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
反序列化操作
//反序列化:将磁盘文件中的对象还原为Java程序中的对象
public void testObjectInputStream(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.data"));
Object o = ois.readObject();
String s=(String )o;//已知的数据类型进行强转
System.out.println(s );
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.如何自定义一个可序列化的类
①需要实现接口Serializable
②当前类提供一个全局常量:SerialVersionUID
③除了当前类实现了Serializable接口外,该类的所有属性都必须是可序列化的;
(基本数据类型,String默认都是可序列化的)
补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
随机存取文件流:RandomAccessFile
使用说明:
1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
2.RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
3.如果RandomAccessFile作为输出流时,
写出到的文件如果不存在,则在执行过程中自动创建。
如果写出到的文件存在,则会对原文件内容进行覆盖。(默认情况下,从头覆盖)
4. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果。seek(int pos)
//对于非文本文件的复制
public void test1(){
RandomAccessFile af = null;
RandomAccessFile rw = null;
try {
af = new RandomAccessFile("total.jpg","r");
rw = new RandomAccessFile("total2.jpg", "rw");
byte[] s=new byte[1024];
int len;
while((len=af.read(s))!=-1){
rw.write(s,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(af!=null){
try {
af.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(rw!=null){
try {
rw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
实现插入文本功能
//对文本文件内容的插入
public void test3(){
RandomAccessFile rw = null;
try {
rw = new RandomAccessFile("hello.txt", "rw");
rw.seek(3);//将指针调到角标为3的位置
//保存3后的内容到StringBuilder中
StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
byte[] s=new byte[20];
int len;
while((len=rw.read(s))!=-1){
builder.append(new String(s ,0,len));
}
//调回指针,写入"java";
rw.seek(3);
rw.write("java".getBytes());
//将StringBuilder中的数据写入到文件中
rw.write(builder.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(rw!=null){
try {
rw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
path、paths、Files的说明
1.NIO的使用说明:
Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的IO API,可以替代标准的Java
IO AP。
NIO与原来的IO同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的(IO是面向流的)、基于
通道的IO操作。
NIO将以更加高效的方式进行文件的读写操作。
随着 JDK 7 的发布,Java对NIO进行了极大的扩展,增强了对文件处理和文件系统特性的支持,以至于我们称他们为 NIO.2。
2.Path的使用 —jdk7提供
2.1Path的说明:
Path替换原有的File类。
2.2如何实例化:
2.3常用方法:
3.Files工具类 —jdk7提供
3.1作用:
操作文件或文件目录的工具类
3.2常用方法: