Stream流

简化集合和数组操作的API

List<String> list =new ArrayList<>();
Collection.addAll(list,"张1","张2","王");
List<String> list2 -new ArrayList<>();
for(String name:list){
if(name.startsWith("张“)){
list.add(name);
}
}
list.Stream().filter(s->s.startsWith("张").filter(s->slength()==2)).forEach(s->System.out.print(s));

技术思想:

  • 先得到一个集合或者数组的Stream流
  • 把元素放到传送带上
  • 然后就使用Stream流简化API来操作元素

Stream的获取

  • 集合获得Stream流的方式

    • 可以用Collection接口中的默认方法Stream()

default Stream stream() 获得当前集合对象的Stream

  • 数组获得Stream流的方式
  • public static Stream stream (T[] array) 获取当前数组的Stream流
  • public static Stream of(T...values) 获得当前的数组/可变数据的Stream流

日志技术

  • 将系统执行的信息选择性的输出到指定的位置
  • 多线程
  • 日志规范
  • 日志框架(JCL slf4j
    • log4j 性能不好
    • JUI
    • Logback加强

logback日志框架

  • logback-core:为其他的模块提供了基础,必须有
  • logback-classic 他是log4j的一个改良版本,同时它实现了slf4j的api
  • logback-access模块和tomcat和jetty等servlet容器集成,已提供http访问日志功能
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="1 seconds"> <contextName>logback</contextName> <property name="log.path" value="F:\\logback.log" /> <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<!-- <filter class="com.example.logback.filter.MyFilter" /> -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender> <appender name="file"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern>
</rollingPolicy> <encoder>
<pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
</pattern>
</encoder>
</appender> <root level="debug">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root> <logger name="com.example.logback" level="warn" /> </configuration>

创建logback的日志对象

public static Looger LOGGER=LoggerFactory.getLogger("Test.class");
LOGGER.debug("main方法开始");
LOGGER.info("我记录的日志第二行");
LOGGER.trace("a="+a);
LOGGER.error("有错误");

配置

输出到控制台:

..

日志级别

trace<debug<info<warn<error

File、方法递归、IO流

  • File类可以定位文件:进行删除、获取文件本身的信息

    • 但是不能读写文件内容
  • IO流可以对硬件中的文件读写

    字节流--音乐视频文件

    字符流---文本文件

File类

java.io.File 代表操作系统的文件对象(文件、文件夹)

  • 定位文件
  • 获取文件本身的信息
  • 删除文件
  • 创建文件

常用方法:

  • public File(String pathname) 根据路径创建文件对象
  • public File (String parent, String Child) 从父路径名字字符和子路径名字字符创建文件对象
  • public File (File parent , String Child) 根据父路径对应文件对象和子路径名字字符串创建文件对象
main(){
//创建File对象
//路径写法:D:\\hjz\\a.jpg
// D:/hjz/a.jpg
//File.separator 分隔符
//相对路径 相对到工程下 "sprngboot/src/data.txt"
File f = new File("D:\\hjz\\a.jpg");
Long a =f.length();//文件的字节大小
f.exists()//判断文件夹是否存在
}

方法:

  • public boolean isDirectory () 测试 抽象路径名表示的File是否为文件夹
  • public boolean isFile()测试 抽象路径名表示的File是否为文件
  • public boolean exists()测试 抽象路径名表示的File是否存在
  • public String getAbsolutePath()返回的抽象路径名的绝对路径名字符串绝对路径
  • public String getPath()将此抽象路径名转化为路径名字符串自己定义的路径
  • public String getName()返回由此抽象名表的文件或文件夹的名称
  • public Long lastModified()返回文件最后修改的时间的毫秒
File f = new File("D:\hjz\a.jpg");

方法:

  • 创建:

    • public boolean createNameFile() 创建一个新的空白文件夹
    • public boolean mkdir()创建一个一级文件夹
    • public boolean mkdirs()创建一个多级文件夹
  • 删除:
    • public boolean delete() 删除由此路径表示的文件、空文件夹

删除非空文件夹要写算法

遍历:

  • public String[] list() 获取当前目录下所有的一级文件夹名称“到一个字符串数组中去返回
  • public File[] listFiles()常用 获取当前目录下所有的“一级文件对象”到一个文件对象数组中去返回重点
    • 不存在返回null
    • 调用者是文件返回null
    • 调用者是一个空文件夹返回一个长度为0的数组
    • 调用者是一个有内容的文件夹时,将里面的所有文件和文件夹的路径放在File数组中返回
    • 包含隐藏内容
File f =new File("D://")
File[] names=f.listFiles();
for(File url:names){
syso(url.getAbsolutePath);
}

方法递归

1.递归公式

2.递归的终结点

3.递归的方向

1-n的阶乘

public static int f(int n){
if(n==1){
return 1;
}else{
return f(n-1)*n;
}
}

1-n的和

public static int f(int n){
if(n==1){
return 1;
}else{
return f(n-1)+n;
}
}

猴子吃桃子

/**
f(x)-f(x)/2-1=f(x+1)
等价变化:
f(x)=2f(x+1)+2
终点
f(10)=1
*/
public static int f(int n){
if(n==10){
return 1;
}else{
return 2*f(n+1)+2;
} }

文件搜索

1.先定位一级文件对象

2.遍历一遍一级文件对象,判断是否文件

3.如果是文件,判断是否是自己想要的

4.如果是文件夹,需要继续递归进去重复上面的过程

public static void searchFile(File dir,String name){
if(dir!=null&&dir.isDirectory){
//可以找了
//获得一级文件对象
File[] files=dir.ListFiles();
//判断一级文件夹的对象
if(files!=null&&files.length>0){
for(File f:files){
//判断当前遍历的一级文件对象是文件还是目录
if(file.isFile()){
//是不是要找的文件
if(file.getName().contains(name)){
System.out.print("找到了文件是"+file.getAbsolutePath());
//启动它
Runtime r =Runtime.getRuntime();
r.exe(file.getAbsolutePath());
}else{
//是文件夹继续递归调用
searchFile(file,fileName);
}
}
}
}
}else{
System.out.print("当前搜索的不是文件夹");
}
}

啤酒问题

盖子换酒,瓶子换酒(套娃)

//买的一共酒
public static int totalNumber;
//记录瓶子的数量
public static int lastBottleNumber;
//记录剩余的盖子数目
public static int lastCoverNumber;
public static void buy(int money){
int buyNumber = money/2;
totalNumber+=buyNumber;
//换成钱
int coverNumber = lastCoverNumber+ buyNumber;
int bottleNumber=lastBottleNumber+buyNumber;
//统计一共多少钱
int allNumber=0;
if(coverNumber>=4){
allNumber+=coverNumber/4*2;
}
lastCoverNumber=coverNumber%4;
if(lastBottleNumber>=2){
allNumber+=(bottleNumber/2)*2
}
lastBottleNumber = bottleNumber%2;
if(allNumber>=2){
buy(allNumber);
}
}

IO流

字符集

  • 计算机底层不能存储字符,只能存储0 1
  • 二进制转化成十进制

ASCII字符集

  • 美国信息交换标准代码:128个字符信息一个字节存储1个字符、一个字节是8位256

GBK字符集

  • 包含了几万个汉字繁体字和日韩文字、兼容ASCII字符编码表一个中文用两个字节

Unicode码表

  • 统一码是计算机科学领域栗的一项业界字符编码UTF-8(中文是以3个字节)\UTF-16

编码前的字符集和编码好的字符集要相同,不然会应为不同的字符位数错误

String编码

  • byte[] getBytes()使用平台的默认字符集将String编码为一系列字节,将结果存储到新的字节数组中
  • byte[] getBytes(String charsetName)使用指定的字符集将该String编码为一系列字节,将结果存储到新的字节数组中

String解码

  • String(byte[] bytes)通过平台的默认字符集解码在指定的字节数组构造新的String
  • String(byte[] bytes,String charsetName)通过指定的字符集解码指定的字节数组来构造新的String
String s ="abc我爱你中国";
byte[] bytes = s.getBytes();//默认编码
byte[] bytes = s.getBytes("GBK");
String ss=new String(bytes);//默认编码
String ss=new String(bytes,"GBK");

IO流:输入输出流读写数据

  • 字节流音乐,视频
  • 字符流文本内容

读入到内存输入流

写入到磁盘输出流

字节流:

  • InputStream

    • FileInputStream

      • public int read() 每次读一个,没有返回-1
      • public int read(byte[] buffer)每次读一个字节数组,没有返回-1
  • OutputStream
    • FileOutPutStream

      • public int write()
      • public int write(byte[] buffers)
      • public int write(byte[] buffers,int pos,int len) 写一部分

字符流:

  • Reader

    • FileReader
  • Writer
    • FileWriter

字节流

FileInputStream

  • 上面的都是抽象类

    • 实现类*水流模型
//1.创建一个输入流管道
//InputStream is =new FileInputStream(new File("D://..."));
//简化
InputStream is =new FileInputStream("D://...");
int b =is.read();//读取一个字节,读完返回-1
Byte[] buffer = new byte[1024];//1kb
InputStream is =new FileInputStream("D://...");
int len =is.read(buffer);
String rs= new String(butter);

常用方法:

Byte[] buffer = new byte[1024];//1kb
InputStream is =new FileInputStream("D://...");
int len=0;
while((len=is.read(butter)!=-1)){
System.out.print(new String(butter,0,len));
}

中文乱码无法解决

//自己暴力实现
Byte[] buffer = new byte[(int)file.length()];//1kb
File file =new File("D://...");
InputStream is =new FileInputStream(file);
int len=0;
while((len=is.read(butter)!=-1)){
System.out.print(new String(butter,0,len));
}
Byte[] buffer = is.readAllBytes();//JDK9出现
File file =new File("D://...");
InputStream is =new FileInputStream(file);
int len=0;
while((len=is.read(butter)!=-1)){
System.out.print(new String(butter,0,len));
}

FileOutPutStream

//写会自动生成
OutputStream os =new FileOutPutStream("D://a.txt");
//OutputStream os =new FileOutPutStream("D://a.txt",true); 追加数据
os.write('a');
os.writ(98);
//写数据必须刷新数据
os.flush();
os.close();//关闭资源
byte[] buffer ={'a',97,98,90};
os.write(buffer);
byte[] buffer ="我是中国人".getBytes("GBK");
os.writer(buffer);
//注意是没有换行的
os.write("\r\n".getBytes());//换行

文件拷贝

学会字节流完成文件的复制--支持一切

try{
//创建一个字节输入流
InputStream is =new FileInputStream("D://img.jpg");
//创建一个字节输出流和目标文件接通
OutputStream os =new FileOutPutStream("D://a.txt");
//定义一个字节数组
byte[] buffer = new byte[1024];
int len ;记录读取数据的字节数
while(len=is.read(buffer)!=-1){
os.write(buffer,0,len);
}
//关闭流
os.close();
is.close();
}catch (Exception ex){
e.printStackTrace();
}

资源释放的方式

   InputStream is=null;
OutputStream os=null; try{
//创建一个字节输入流
is =new FileInputStream("D://img.jpg");
//创建一个字节输出流和目标文件接通
os =new FileOutPutStream("D://a.txt");
//定义一个字节数组
byte[] buffer = new byte[1024];
int len ;记录读取数据的字节数
while(len=is.read(buffer)!=-1){
os.write(buffer,0,len);
} }catch (Exception ex){
e.printStackTrace();
}finally{
//关闭流
//下面都要try ---catch---try{..}catch{...}
//非空校验 if(os!=null){os.close()}
os.close();
is.close();
}

JDK7:

try(
//创建一个字节输入流
InputStream is =new FileInputStream("D://img.jpg");
//创建一个字节输出流和目标文件接通
OutputStream os =new FileOutPutStream("D://a.txt");
){
//定义一个字节数组
byte[] buffer = new byte[1024];
int len ;记录读取数据的字节数
while(len=is.read(buffer)!=-1){
os.write(buffer,0,len);
}
//关闭流
os.close();
is.close();
}catch (Exception ex){
e.printStackTrace();
}

JDK9:

不好

字符流

  • Reader

    • FileReader
  • Writer
    • FileWriter
Reader fr=new FileReader("D://img.txt");
Writer fw=new FileWriter("D://a.txt");
int code = fr.read();//每次读取一个字符 没有返回-1

FileReader

  • public FileReader(File file)
  • public FileReader(String pathname)

常用方法:

  • public int read()每次读取一个字符 没有返回-1
  • public int read(char[] buffer)每次读取一个字符数组 没有返回-1

问题:

  • 中文不会乱码
  • 性能较慢

Filewrite

  • public FileWriter(File file)
  • public FileWriter(File file,boolean append)
  • public FileWriter(String pathname)
  • public FileWriter(String pathname,boolean append)

常用方法:

  • public void write(int c)
  • public void write(char[] cbuf)
  • public void write(char[] cbuf,int off,int len)写一部分
  • public void write(String str)
  • public void write((String str,int off,int len)
  • flush()
  • close()
Write fw =new FileWrite("D://img.jpg");
fw.write('s');

缓冲流

自带缓冲区,提高原始流的性能

  • BufferedInputStream
  • BufferedOutputStream
  • BufferedReader
  • BufferedWriter

自带了8kb的缓冲池

字节缓冲流

构造器:

  • public BufferedInputStream (InputStream is)
  • public BufferedOutputStream(OutputStream os)
try(
//创建一个字节输入流
InputStream is =new FileInputStream("D://img.jpg");
BufferedInputStream bis =new BufferedInputStream(is);
//创建一个字节输出流和目标文件接通
OutputStream os =new FileOutPutStream("D://a.txt");
BufferedOutputStream ois=new BufferedOutputStream(os);
){
//定义一个字节数组
byte[] buffer = new byte[1024];
int len ;记录读取数据的字节数
while(len=bis.read(buffer)!=-1){
bos.write(buffer,0,len);
}
}catch (Exception ex){
e.printStackTrace();
}

字符缓冲流:

  • public BufferedReader (Read is)
  • public BufferedWriter(Writer os)

新增输入流方法:

  • public String readLine() 读取一行数据,如果没有完毕,无行课读取返回null

输出流:

  • public void newLine() 换行操作

转换流

不同编码读取会乱码

  • 使用字符输入转换流
  • 先提取原始的字节流
  • 然后在将字节流转换成对应的编码格式

转换流:

  • InputStreamReader
  • OutputStreamWriter

构造器:

  • public InputStreamReader (InputStream is)
  • public InputStreamReader(InputStream is,String charset)

字符输出转换流:

  • public OutputStreamWriter (OutputStream os)
  • public OutputStreamWriter(OutputStream os,String charset)

序列化对象

对象字节输出流

ObjectOutputStream

对象字节输入流

ObjectInputStream

构造器:

  • public ObjectOutputStream (OutputStream os)
  • public ObjectInputStream (InputStream is)
//对象系列化
//实体类要实现接口
Serialiazble
Student st =new Student (...);
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream("D://a.txt"));
//调用序列化方法
oos.writeObject(st);
oos.close();
//对象反序列化
ObjectInputStream ois = new ObjectInputStream(new FileOutputStream("D://a.txt"));
//调用序列化方法
Student st=( Student)ois.readObject(st);
ois.close();

不想序列化

//实体类属性字段加
private transient String password;

打印流

字节输出流;

PrintStream

字符输出流

PrintWriter

PrintStream

构造器:

  • public PrintStream(OutputStream os)
  • public PrintStream(File file)
  • public PrintStream(String filePath)

方法:

  • public void print(XXX xxx)

PrintWriter

构造器:

  • public PrintWriter(OutputStream os)
  • public PrintWriter(File file)
  • public PrintWriter(String filePath)

方法:

  • public void print(XXX xxx)
 PrintStream ps =new  PrintStream("D://s。text");

Propreties

  • 是一个Map集合,但是HashMap更好用

存放键值对的信息

Propreties ps =new Propreties();
ps.setPropreties("admin","123456");
ps.put("password","123456");
ps.store(new FileWriter("D://a.txt","give me 100"));
//路径,心得
//加载属性到Propreties对象中
ps.load(new FileReader("D://a.txt"));
ps.get("admin");
ps.getPropreties("admin");

IO框架

我醉了经典白学

commonis-io

FileUtils

  • String readFileToString(File file,String encoding) 读取文件中的数据,返回字符串
  • void copyFile(File srcfile,File destFile) 复制文件
  • void copyDirectoryToDirectory(File srcDir,File destDir) 复制文件夹

NIO

Files.copy(Path.of(""),Path.of(""));
Files.deleteIfExists(Path.of(""))

javaEE(Stream流、日志、IO流、File)的更多相关文章

  1. File流与IO流 看这一篇就够了

    主要内容 File类 递归 IO流 字节流 字符流 异常处理 Properties 缓冲流 转换流 序列化流 打印流 学习目标 [ ] 能够说出File对象的创建方式 [ ] 能够说出File类获取名 ...

  2. javaIO--数据流之IO流与字节流

    0.IO流 0.1.IO(Input Output)流的概念 Java中将不同设备之间的数据传输抽象为“流”:Stream设备指的是:磁盘上的文件,网络连接,另一个主机等等 按流向分:输入流,输出流: ...

  3. Java学习笔记33(IO:打印流,IO流工具类)

    打印流: 有两个类:PrintStream     PrintWriter类,两个类的方法一样,构造方法不一样 PrintStream构造方法:接收File类型,接收字符串文件名,接收字节输出流(Ou ...

  4. io流(io流的引入与文件字节流)

    io流的引入与文件字节流 io流:就是一根吸管,插入后,可以操作目标文件 io流的分类: 按方向:输入,输出 按大小:字节,字符 按处理方式: 处理流:"管套着管" --- 流结合 ...

  5. IO异常--缓冲流--转换流--序列化流( IO流2 )

    1.IO异常的处理 JDK7前处理:使用try...catch...finally 代码块,处理异常部分 // 声明变量 FileWriter fw = null; try { //创建流对象 fw ...

  6. Java学习笔记43(打印流、IO流工具类简单介绍)

    打印流: 有两个类:PrintStream,PrintWriter类,两个类的方法一致,区别在于构造器 PrintStream:构造方法:接收File类型,接收字符串文件名,接收字节输出流(Outpu ...

  7. IO流——常用IO流详解

    1:字节流 字节流:用于处理以字节为单位的二进制文件(如音乐,图片等) InputStream 是抽象类 它的对应子类FileInputStream可以被实例化 构造方法: FileInputStre ...

  8. java 输入输出IO流 IO异常处理try(IO流定义){IO流使用}catch(异常){处理异常}finally{死了都要干}

    IO异常处理 之前我们写代码的时候都是直接抛出异常,但是我们试想一下,如果我们打开了一个流,在关闭之前程序抛出了异常,那我们还怎么关闭呢?这个时候我们就要用到异常处理了. try-with-resou ...

  9. IO流4 --- IO流体系 --- 技术搬运工(尚硅谷)

  10. day21<IO流+&FIle递归>

    IO流(字符流FileReader) IO流(字符流FileWriter) IO流(字符流的拷贝) IO流(什么情况下使用字符流) IO流(字符流是否可以拷贝非纯文本的文件) IO流(自定义字符数组的 ...

随机推荐

  1. Execute Crond Service on openEuler

    一.Execute Crond Service on openEuler 1 crond 概述 crond就是计划任务/定时任务 常见有闹钟.PC端定时关机 shutdown -s -t 200,定时 ...

  2. jmeter ORA-00911: invalid character报错解决方法

    今天通过jmeter进行Oracle数据库操作时,遇到一个小坑. 解决办法:去掉sql最后的分号.

  3. python-函数的参数与返回值

    Python函数 4.1.函数初识 在编写程序的过程中,有某一功能代码块出现多次,但是为了提高编写的效率以及代码的重用,所以把具有独立功能的代码块组织为一个小模块,这就是函数 就是一系列Python语 ...

  4. linux系统编码修改

    1. 查看当前系统默认采用的字符集locale 2. 查看系统当前编码echo $LANG如果输出为:en_US.UTF-8     英文zh_CN.UTF-8     中文 3. 查看系统是否安装中 ...

  5. ArcObjects SDK开发 011 RasterLayer

    1.RasterLayer的结构 图层的话,除了FeatureLayer外,用的最多的就是RasterLayer了.较FeatureLayer而言,RasterLayer比较简单,这点可以从栅格图层的 ...

  6. 【Java】二分查找标准代码

    太菜了..写不出正确的... 干脆放一个标准代码,之后参考 boolean BinarySearch(int[] m){ int l=0,r=m.length-1;//减1相当于数组两头(lr都能指到 ...

  7. MySQL存储 pymysql模块

    目录 pymysql模块 基本使用 cursor=pymysql.cursors.DictCursor 获取数据 fetchall 移动光标 scroll 增删改二次确认 commit autocom ...

  8. 如何使用ChatGPT来自动化Python任务

    1.概述 最近,比较火热的ChatGPT很受欢迎.今天,笔者为大家来介绍一下ChatGPT能做哪些事情. 2.内容 ChatGPT是一款由OpenAI开发的专门从事对话的AI聊天机器人.它的目标是让A ...

  9. [编程基础] C++多线程入门10-packaged_task示例

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++11标准. 文章目录 10 pa ...

  10. 更改json节点key

    json节点key更改,给朋友写的小tool,顺便记录一下 单个指定 每一个需要修改的key,都需要指定 /** * 需要转义的key对象 * 原key: 新key */ const jsonKeys ...