常用类+IO流

常用类

日期类

常用日期相关类
在这里插入图片描述
当前时间

//当前毫秒数 
long timeNum =System.currentTimeMillis(); System.out.println(timeNum); 
//当前日期 
Date nowDate =new Date(); System.out.println(date);

Date

//0 时间点 东八区 1970年1月1日 08:00:0 
Date date =new Date(0L); System.out.println(date); 
//指定一个时间 
Date myDate =new Date(189712329239L); System.out.println(myDate); System.out.println(myDate.getTime()); //获取长整型数字 
//修改时间 
myDate.setTime(0L); System.out.println(myDate);

SimpleDateFormat
日期格式化,在日期格式化的过程中,会用到模板,这个在api中有详细说明
在这里插入图片描述
字符串的表示形式与日期互换,使用日期转换器SimpleDateFormat ,代码如下:

public static void main(String[] args) throws ParseException { 
Date myDate2 =new Date(0L); 
//字符串的形式 
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
//转字符串 
String dateStr =dateFormat.format(myDate2); System.out.println(dateStr); 
//转成日期 
myDate = dateFormat.parse("2020-02-25 11:16:30"); 
//这里有异常 System.out.println(myDate.getTime()); 
}

java8日期相关的常用api

在这里插入图片描述

//今年 
System.out.println("今年"+Year.now()); 
//6月 
System.out.println("月份:"+Month.FEBRUARY); //今天不包含时分秒
LocalDate today = LocalDate.now(); System.out.println("今天:"+today); 
//此时此刻 
LocalDateTime now = LocalDateTime.now(); System.out.println("现在:"+now); 
//您的生日 
LocalDate yourBirthDate = LocalDate.of(1999, Month.JUNE, 15); 
System.out.println("生日:"+yourBirthDate); 
//您的学习时间
LocalDateTime dateTime = LocalDateTime.of(2020, 2, 25, 12, 30,40); System.out.println("时间:"+dateTime);

jdk8的间隔类(了解即可)

LocalDate today = LocalDate.now(); 
LocalDate birthDate = LocalDate.of(1999, 3, 15); 
//时期间隔 年月日 
Period p = Period.between(birthDate, today);
System.out.printf(p.getYears()+"年"+p.getMonths()+"d"+p.getDays()+"日"); 
LocalDate startDate = LocalDate.of(1993, 8, 19); 
LocalDate endDate = LocalDate.of(1994, Month.JANUARY,16); 
//期量单位 间隔 
long between=ChronoUnit.YEARS.between(startDate, endDate); System.out.println("两年之间的差 : " + between); 
//0 不是1不满一年不计算在内 between =ChronoUnit.MONTHS.between(startDate, endDate); 
System.out.println("两月之间的差 : " + between); 
//4 不是5不满一月不计算在内 
//瞬间 
Instant inst1 = Instant.now(); 
Instant inst2 = inst1.minus(Duration.ofSeconds(10)); System.out.println("毫秒相隔 : " + Duration.between(inst1, inst2).toMillis()); System.out.println("秒相隔 : " + Duration.between(inst1, inst2).getSeconds());

Math类

在这里插入图片描述

枚举

java枚举类可以简单地理解为一种特殊的java类 。通过关键字 enum实现,自动继承自Enum类(枚举类)

public enum Color{
RED,GREEN, YELLOW; 
}
public class Test{ 
public static void main(String[] args){ System.out.println(Color.RED); 
} 
   }

其中每一个数据,都是枚举类的实例 作为类型安全的常量 可以实现接口拓展功能 将枚举数据与它的常量关联起来
将枚举数据和它的行为关联起来(特定于常量的方法实现)

File类

File 代表文件和目录路径名的抽象表示形式
File 类的常见构造方法:public File(String pathname)
以 pathname 为路径创建 File 对象,如果 pathname 是相对路径,则默认的当前路径在系 统属性 user.dir 中存储。 File 的静态属性 separator 存储了当前系统的路径分隔符。
常见的方法:

public boolean canRead() 
public boolean canWrite() 
public boolean exists() 
public boolean isDirectory() 
public boolean isFile() 
public boolean isHidden() 
public long lastModified() 
public long length() 
public String getName() 
public String getPath()

代码示例:

import java.io.File; 

/** * 程序 -->文件 需要建立联系 * 抽象为 File 类 * * 1、文件夹 与文件 抽象-->File * 2、分割符: * 路径分隔符: ; pathSeparator * 目录分隔符: \ / separator * 静态常量: * * 1、构建 File File(String pathname) * File(File parent, String child) * File(String parent, String child) **/ public class FileDemo01 { /*** @param args */ 
public static void main(String[] args) { System.out.println(File.pathSeparator); System.out.println(File.separator); 
//绝对路径 与文件建立联系 
File src = new File("E:\\test\\03.gif"); 
src = new File("E:/test/03.gif"); 
src = new  File("E:"+File.separator+"test"+File.separator+"03.gif"); System.out.println(src.exists()); 
//相对路径 File src2 = new File("E:/test","03.gif"); 
src2 = new File(new File("E:/test"),"03.gif"); System.out.println(src.exists());
 }
    }
import java.io.File; import java.io.FilenameFilter; import java.io.IOException; /** * 1、创建对象 new File(完整路径) -->绝对路径 new File(上级路径,本名); -->相对 路径 new File(上级抽象表示形式, 本名) 2、方法 1)区分目录 or 文件 isFile() isDirectory() 2)获取路径 名称 getPath() getAbsolutePath() getName() 3)判断文件是否存在 exists() 4)创建文件 createNewFile() 5)创建目录 mkdir() -->创建一层,确保父路径存在,如果父路径不存在,不 能创建 mkdirs() -->父路径不存在,全部创建 6)列表 listFiles() 7)删除文件 delete() ***/ public class FileDemo02 { 
public static void main(String[] args) throws IOException { 
File src2 = new File("E:/test","03.gif"); boolean flag =src2.isFile(); 
//是否 为文件
flag =src2.isDirectory(); System.out.println(flag); 
//获取文件名称或路径 
String name = src2.getName(); System.out.println(name); 
String path = src2.getPath(); 
path = src2.getAbsolutePath(); System.out.println(path); 
//文件是否存在 
flag = src2.exists(); 
if(!flag){ 
//不存在创建 
src2.createNewFile(); 
} 
//创建目录 
src2 = new File("E:/test/test2/test3"); src2.mkdir(); 
//确保父路径存在,才能创建 
src2.mkdirs();
// 如果父路径不存在,则创建 
//列出当前文件夹的子目录 
src2 = new File("E:/xp/20130401"); if(src2.isDirectory()){ 
//目录才有子目录 
File[] subFiles = src2.listFiles(new FilenameFilter(){ 
@Override 
public boolean accept(File dir, String name) { 
/*System.out.println(name); if(name.contains("xls")){ 
return true; 
}*/ 
return !new File(dir,name).isDirectory(); 
}
}); for(File temp:subFiles){ System.out.println(temp); 
}
}
//delete()
src2 = new File("E:/test","03.gif"); 
boolean flag2 =src2.delete(); System.out.println(flag2); 
}
}

通过 File 对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下)。

public boolean createNewFile()throws IOException 
public boolean delete() 
public boolean mkdir() mkdirs() 
/** *递归打印文件夹 */
public static void printName(File src){ if(null ==src){ 
return; 
}
System.out.println(src.getPath()); if(src.isDirectory()){ 
for(File sub:src.listFiles()){ printName(sub); 
} 
} }

IO流

关系图
在这里插入图片描述
操作 IO流的步骤:

1)、建立联系
2)、选择流
3)、操作:写出 读取
4)、释放资源(程序中打开的文件 IO 资源不属于内存中的资源,垃圾回收无法回收,需要显示关闭。)

输入流

抽象类:InputStream 和 Reader
在这里插入图片描述
文件节点类: FileInputStream 和 FileReader
单个字节读取

public class SingleFileRead { 
public static void main(String[] args) { 
// 1、建立联系 File对象 
File file = new File("f:/IO/test.txt"); 
// 2、选择流 
InputStream in = null;
// 提升作用域 
try {
in = new FileInputStream(file); 
// 3、操作 单个字节读取 
long fileLength = file.length(); 
// 接收实际读取的字节数 
// 计数器 
System.out.println(fileLength); 
long num = 0; 
// 循环读取 
while (num < fileLength) { 
char ch = (char) in.read(); System.out.println(ch); 
num++; 
} 
} catch (FileNotFoundException e) { 
// TODO Auto-generated catch block e.printStackTrace(); 
System.out.println("文件不存在,不能进行下一步操作"); } catch (IOException e) { 
// TODO Auto-generated catch block e.printStackTrace(); 
System.out.println("读取文件失败"); 
} finally { 
try {
// 4、释放资料 
if (in != null) { 
in.close(); 
} 
} catch (IOException e) { 
// TODO Auto-generated catch block e.printStackTrace(); 
System.out.println("关闭文件输入流失败"); 
} 
             } 
   } 
}

批量读取

public class ReadFile { 
public static void main(String[] args) {
//1、字节读取:建立联系 File对象 
File file=new File("f:/IO/test.txt"); 
//2、选择流 
InputStream in=null;
//提升作用域 
try {in=new FileInputStream(file); 
//3、操作 不断读取 缓冲数组 
byte[]car=new byte[1024]; 
int len=0; //接收实际读取的大小 
//循环读取 
while(-1!=(len=in.read(car))){ 
//输出,字节数组转成字符串 
String info=new String(car,0,len); System.out.println(info);
 } 
 } catch (FileNotFoundException e) { 
 // TODO Auto-generated catch block e.printStackTrace(); 
 System.out.println("文件不存在"); 
 } catch (IOException e) { 
 // TODO Auto-generated catch block e.printStackTrace(); 
 System.out.println("读取文件失败"); 
 }finally{ 
 try {
 //4、释放资料 
 if(in!=null){ 
 in.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("关闭文件输入流失败"); } } } }
 //字符读取1、创建源 
 File src=new File("f:/char.txt"); 
 //2、选择流
Reader reader=new FileReader(src); 
//3、读取操作 
char[] flush=new char[1024]; 
int len=0; while(-1!=(len=reader.read(flush))){
 //字符数组转换为字符串 
 String str=new String(flush,0,len); System.out.println(str); } 
 //4、释放资源
 reader.close();

输出流

抽象类:OutputStream 和 Writer
在这里插入图片描述
在这里插入图片描述
文件节点类: FileOutputStream 和 FileWriter

FileOutputStream 和 FileWriter,它们都是节点流,直接和指定文件关联。

public class WriteFile { 
public static void main(String[] args) { //1、建立联系 File对象 源头 目的地 
File dest=new File("c:/IO/print.txt"); 
//2、选择流 文件输出流 
OutputStream FileOutputStream OutputStream out=null; 
//以追加形式写出文件 必须为true 否则会覆盖 
try {
out=new FileOutputStream(dest,true); 
//3、操作 
String str="shsxt is very good \r\n good good good"; 
//字符串转成字节数组 
byte[] data=str.getBytes(); out.write(data,0,data.length); out.flush();//强制刷新出去 } catch (FileNotFoundException e) { 
// TODO Auto-generated catch block e.printStackTrace(); 
System.out.println("文件未找到"); 
} catch (IOException e) { 
// TODO Auto-generated catch block e.printStackTrace(); 
System.out.println("文件写出失败"); 
}finally{ 
try {if(out!=null){ 
out.close(); 
} 
} catch (IOException e) { 
// TODO Auto-generated catch block e.printStackTrace(); 
System.out.println("关闭输出流失败"); } } } }
//1、创建源 
File dest=new File("f:/IO/char.txt");
//2、选择流 Writer wr=new FileWriter(dest,true); 
//3、写出 String str="锄禾日当午\r\n码农真辛苦\r\n一本小破书\r\n一读一上午"; 
wr.write(str); 
//追加内容 wr.append("我就是追加进去的"); wr.flush();//强制刷出 
//4、关闭资源 
wr.close();

结合输入输出流,可以实现文件拷贝

public static void copyFile(String srcPath, String destPath) throws FileNotFoundException,IOException{ 
// 1、建立联系 源(存在且为文件) 目的地(文件可以不存在) 
File src = new File(srcPath); 
File dest = new File(destPath); if(!src.isFile()){
//不是文件或者为null时抛出异常 System.out.println("只能拷贝文件"); 
throw new IOException("只能拷贝文件"); }
// 2、选择流 
InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); 
// 3、操作 
byte[] flush = new byte[1024]; 
int len = 0; 
// 读取 
while (-1 != (len = in.read(flush))) { 
// 写出 
out.write(flush, 0, len); 
}out.flush();// 强制刷出 
// 关闭流 先打开的后关闭 
out.close(); 
in.close(); }

缓冲处理类:BufferedInputStream和 BufferedReader(重 点)

缓冲流

缓冲提高性能: 字节流直接套上即可;字符缓冲流 +新增方法(不能使用多态):

//1、创建源,建立联系 
File src =new File("test.txt"); 
//2、选择缓冲流 
InputStream is =new BufferedInputStream(new FileInputStream(src)); 
//3、操作 : 多个读取 
byte[] car =new byte[2]; 
int len =0; while(-1!=(len=is.read(car))){ //获取数组的内容 字节数组转字符串 
new String(字节数组,0,length) System.out.println(new String(car,0,len)); }
//4、释放资源 
is.close(); 
//创建源: 
File src =new File("test.txt"); 
//使用字符缓冲流 提高性能读取文件 +新增方法(不能使用多态) 
BufferedReader br =new BufferedReader(new FileReader(src)); 
//操作 行读取
String line=null; while(null!=(line=br.readLine())){ System.out.println(line); }
//释放资源 
br.close();

转换处理流: InputStreamReader

转换流:将字节流转为字符流 处理乱码(编码集、解码集)。

//读取文件 
File src =new File("test.txt"); 
//转换流 
BufferedReader br =new BufferedReader( new InputStreamReader(new BufferedInputStream(new FileInputStream(src)),"utf-8" ) ); 
//行读取 
String msg =null; 
while(null!=(msg =br.readLine())){ System.out.println(msg); }
br.close();

数据处理流:DataInputStream

可以处理基本类型+String,保留数据的类型。前提是读取顺序与写出顺序一致,否则读取数据不正确

/** * 数据+类型 输出到文件 * @param destPath * @throws IOException */
public static void write(String destPath) throws IOException{ 
int point = 2; 
long num = 100L; 
String str = "数据类型"; 
//创建源 
File dest = new File(destPath); 
//选择流 
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest))); 
//操作 写出的顺序 为读取作准备 dos.writeInt(point); 
dos.writeLong(num); 
dos.writeUTF(str); 
dos.flush(); 
//释放资源

dos.close(); }

对象流

以前我们学过的流都只能读写字节,字符形式的数据,而java中非常重要并且常见的对象类型的数据,如果想要存储到文件中应该怎么操作呢?这个时候就使用到了对象流。
序列化:是一个用于将对象状态转换为字节流的过程,可以将其保存到磁盘文件中或通过网络发送到任何其他程序
反序列化:从字节流创建对象的相反的过程称为 反序列化
对象处理流(反序列化):ObjectInputStream
ObjectInputStream能够让你从输入流中读取Java对象,而不需要每次读取一个字节。你可以把InputStream包装到ObjectInputStream中,然后就可以从中读取对象了
首先在使用ObjectInputStream和ObjectOutputStream的时候,放置在此IO中的对象,必须要实现Serializable接口!序列化接口(实现了此接口,代表我们的对象支持序列化)
但是实现了Serializable接口之后,其中并没有实现任何方法,对于这种接口,我们称之为标记接口。

/** * 反序列化: * 1、先写入再读取 * 2、读取对象需要知道具体类型,依次读取 * 注意: * 1)不是所有的对象都可以序列化 Serializable * 2)不是所有的属性都需要序列化 transient */
public static void read(String srcPath) throws FileNotFoundException, IOException, ClassNotFoundException{ 
//创建源 
File src=new File(srcPath); 
//选择流 
OjbectInputStream ObjectInputStream dis=new ObjectInputStream( new BufferedInputStream( new FileInputStream(src) ) ); 
//操作 读取的顺序与写出的顺序一致 必须存在才能读取 
Object obj=dis.readObject(); 
if(obj instanceof Employee){ 
Employee emp=(Employee)obj; System.out.println(emp.getName()); System.out.println(emp.getSalary()); }
obj=dis.readObject(); 
int[]arr=(int[])obj;
释放资源 
dis.close(); }

ObjectOutputStream(序列化)
注意: 要先序列化后反序列化

//创建源 
File dest=new File(destPath); 
//选择流 
OjbectOutputStream ObjectOutputStream dos=new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(dest)) );
//操作 读取的顺序与写出的顺序一致 必须存在才能读取 
Employee obj=new Employee ("yinwei",1500); dos.writeObject(obj); 
//刷出 
dos.flush(); 
//释放资源 
dos.close();
发布了22 篇原创文章 · 获赞 6 · 访问量 452

猜你喜欢

转载自blog.csdn.net/ffgyfgj/article/details/105228075