io基础入门

压缩的封装

参考:https://blog.csdn.net/qq_29897369/article/details/120407125?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-0-120407125-blog-120163063.235v38pc_relevant_sort_base3&spm=1001.2101.3001.4242.1&utm_relevant_index=3

输入流读取文字符串

IoUtils.read(is, "utf-8");
IOUtils.copy(is, new FileOutputStream(file));

Resource

Java的标准java.net.URL类和各种URL前缀的标准处理程序还不足以满足对所有低级资源的访问;Resource接口在Spring和Spring中被大量使用
用实用程序类:资源抽象不能取代功能。它尽可能地包装它。例如,UrlResource包装一个URL,并使用包装的URL来完成它的工作

Spring包括几个内置的资源实现:

UrlResource

UrlResource包装了一个java.net.URL,可用于访问通常可以通过URL访问的任何对象,如文件、HTTPS目标、FTP目标等
路径字符串包含一个众所周知的(对属性编辑器来说)前缀(例如classpath:),它将为该前缀创建一个适当的专门化资源;
如果它不识别前缀,则假定该字符串是标准URL字符串并创建UrlResource;

ClassPathResource

该类表示应该从类路径获得的资源
JavaBeans PropertyEditor识别字符串路径上的特殊前缀classpath:,并在这种情况下创建ClassPathResource;

/**
getPath: 返回此资源的路径:a.txt
getAbsolutePath: /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/test-classes/a.txt
**/
@Test
public void demo3(){
    ClassPathResource classPathResource = new ClassPathResource("a.txt");
    System.out.println(classPathResource.getPath());
    try {
        System.out.println(classPathResource.getFile().getAbsolutePath());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

test-classes和classes的区别:一个是@test资源resources和一个是项目资源resources
注意: 如果test-classes和classes资源不存在需要,maven重新install

FileSystemResource

这是java.io.File句柄的Resource实现
支持文件解析和URL解析;

PathResource

是一个纯粹的基于java.nio.path.Path的FileSystemResource替代品

ServletContextResource

这是ServletContext资源的Resource实现,用于解释相关web应用程序根目录中的相对路径。

InputStreamResource

InputStreamResource是给定InputStream的资源实现

ByteArrayResource

这是给定字节数组的Resource实现。它为给定的字节数组创建一个ByteArrayInputStream。

ResourceLoader

所有应用程序上下文实现ResourceLoader接口。因此,所有应用程序上下文都可以用于获取Resource实例。
会为每个上下文返回适当的对象。(ServletContextResource,FileSystemResource)
可以通过指定任何标准java.net.URL前缀来强制使用UrlResource。使用文件和https前缀的示例如下:

Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt");

classpath:
classpath:com/myapp/config.xml
file:
file:///data/config.xml
https:
https://myserver/logo.png
/data/config.xml:
取决于底层的ApplicationContext。

ResourcePatternResolver

Ant-style路径模式解析为资源对象

PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resourcePatternResolver.getResources(mapperLocations);
        sqlSessionFactoryBean.setMapperLocations(resources);
@Test
public void demo4() {
    PathMatchingResourcePatternResolver resource = new PathMatchingResourcePatternResolver();
    Resource resource1 = resource.getResource("classpath:a.txt");
    try {
        System.out.println(resource1.getFile().getAbsolutePath());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    try {
        Resource[] resources = resource.getResources("*.txt");
        for (Resource resource2 : resources) {
            System.out.println(resource2.getFile().getAbsolutePath());
//                        /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/test-classes/a.txt
//                        /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/test-classes/b.txt
//                        /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/test-classes/c.txt
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

classpath*:

classpath*:/config/beans.xml

您还可以依赖于ResourceLoader的自动装配,作为实现ResourceLoaderAware接口的替代方案。

资源路径没有前缀,根据应用程序上下文的确切类型;
如果需要强制使用特定的资源类型,可以使用前缀

@Component
public class MyBean {

    private final Resource template;

    public MyBean(@Value("${template.path}") Resource template) {
        this.template = template;
    }

    // ...
}

Ant-style Patterns

/WEB-INF/-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/
-context.xml
classpath:com/mycompany/**/applicationContext.xml

通配符类路径依赖于底层ClassLoader的getResources()方法

相对路径相对于当前工作目录,而绝对路径相对于文件系统的根目录

hutool加载资源

import cn.hutool.setting.dialect.Props;


Props props = new Props("demo.properties");
System.out.println(props.get("name"));

类加载器加载资源

// 路径 /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/src/main/java
package com.wx.utils.Demo
public class Demo {
	public static void main(String[] args) {
	    System.out.println(Demo.class.getClassLoader().getResource("").getPath());
	    // /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/classes/
	    System.out.println(Demo.class.getClassLoader().getResource("application.yml").getPath());
	    // /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/classes/application.yml
	    System.out.println(Demo.class.getClassLoader().getResource("com/wx/WxApplication.class").getPath());
	    // /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/classes/com/wx/WxApplication.class
	
	    System.out.println(Demo.class.getResource("").getPath());
	    // /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/classes/com/wx/utils/
	    System.out.println(Demo.class.getResource("Demo.class").getPath());
	   // /Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/target/classes/com/wx/utils/Demo.class
	
	    InputStream is = Demo.class.getClassLoader().getResourceAsStream("demo.properties");
	
	    Properties properties = new Properties();
	    try {
	        properties.load(is);
	        System.out.println(properties.get("name"));
	    } catch (IOException e) {
	        throw new RuntimeException(e);
	    }
	}
}

demo.properties

name=zjy

在这里插入图片描述

File类

参考: https://www.ydlclass.com/doc21xnv/java/first/javase/12%E3%80%81IO%E6%B5%81/#_6%E3%80%81file%E7%B1%BB%E7%9A%84%E8%8E%B7%E5%8F%96%E5%8A%9F%E8%83%BD%E5%92%8C%E4%BF%AE%E6%94%B9%E5%90%8D%E5%AD%97%E5%8A%9F%E8%83%BD
​ 在 Java 中,File 类是 java.io 包中唯一代表磁盘文件本身的对象。File 类定义了一些与平台无关的方法来操作文件,File类主要用来获取或处理与磁盘文件相关的信息,像文件名、 文件路径、访问权限和修改日期等,还可以浏览子目录层次结构。   File 类表示处理文件和文件系统的相关信息。也就是说,File 类不具有从文件读取信息和向文件写入信息的功能,它仅描述文件本身的属性。
File(String pathname)
File(File parent,String child)
File file = new File(“D:\code\a.txt”);
File file = new File(“D:\code”);
File child = new File(file,“a.txt”);

File类创建和删除功能

boolean createNewFile() 指定路径不存在该文件时创建文件,返回true 否则false
boolean mkdir() 当指定的单击文件夹不存在时创建文件夹并返回true 否则false
boolean mkdirs() 当指定的多级文件夹在某一级文件夹不存在时,创建多级文件夹并返回true 否则false
boolean delete() 删除文件或者删除单级文件夹

File类的判断功能

boolean exists() 判断指定路径的文件或文件夹是否为空
boolean isAbsolute() 判断当前路径是否是绝对路径
boolean isDirectory() 判断当前的目录是否存在
boolean isFile() 判断当前的目录是否是一个文件
boolean isHidden() 判断当前路径是否是一隐藏文件

File类的获取功能和修改名字功能

File getAbsoluteFile() 获取文件的绝对路径,返回File对象
String getAbsolutePath() 获取文件的绝对路径,返回路径的字符串
String getParent() 获取当前路径的父级路径,以字符串形式返回该父级路径
String getName() 获取文件或文件夹的名称
String getPath() 获取File对象中封装的路径
long lastModified() 以毫秒值返回最后修改时间
long length() 返回文件的字节数
boolean renameTo(File dest) 将当前File对象所指向的路径修改为指定File所指向的路径

文件夹列表操作

返回值 方法 描述
String list() 得到这个文件夹下的所有文件,返回路径数组
String[] list(FilenameFilter filter) 通过过滤器过滤文件,过滤通过文件名过滤,返回路径数组
File[] listFiles() 得到这个文件夹下的所有文件,返回文件数组
File[] listFiles(FileFilter filter) 通过过滤器过滤文件,过滤通过文件过滤,返回文件数组
File[] listFiles(FilenameFilter filter) 通过过滤器过滤文件,过滤通过文件名过滤,返回文件数组

public class FileTest {
    @Test
    public void demo(){
        getImageName(new File("/Users/yyyyjinying/Downloads"));
    }

    private void getImageName(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    if (dir.isDirectory() || dir.getName().endsWith(".png")) {
                        return true;

                    }
                    return false;
                }
            });

            for (File file1 : files) {
                getImageName(file1);
            }

        } else if(file.getName().endsWith(".png")) {
            System.out.println(file.getName());
        }
    }
}

IO流

输入流和输出流:是否写入程序内存;
字节流和字符流:是一个字节一个字节的读取或写入

分类字节输入流字节输出流字符输入流字符输出流
抽象基类InputStreamOutputStreamReaderWriter
访问文件FileInputStreamFileOutputStreamFileReaderFileWriter
访问数组ByteArrayInputStreamByteArrayOutputStreamCharArrayReaderCharArrayWriter
访问字符串StringReaderStringWriter
缓冲流(处理)BufferedInputStreamBufferedOutputStreamBufferedReaderBufferedWriter
操作对象ObjectInputStreamObjectOutputStream

一个流读完了就没有了,就不能在读了

字节流通过InputStreamReader转化为字符流

// 字节流通过InputStreamReader转化为字符流,通过BufferedReader处理流
 BufferedReader reader = new BufferedReader(new InputStreamReader(tarArchiveInputStream));
String line;
while ((line = reader.readLine()) != null) {
    list.add(line);
}

字符流通过ByteArrayInputStream转化为字节流

List<String> list = Arrays.asList("Hello", "world!");
StringBuilder builder = new StringBuilder();
list.forEach(item -> {
   builder.append(item);
   builder.append("\n");
});
String str = builder.toString();
byteArrayInputStream = new ByteArrayInputStream(str.getBytes());
bufferedInputStream = new BufferedInputStream(byteArrayInputStream);

集合字符串输入文件中

List<String> list = Arrays.asList("Hello", "world!");

String str = builder.toString();
File tempFile = File.createTempFile("demo8", ".txt");
// 第一种
StringBuilder builder = new StringBuilder();
list.forEach(item -> {
   builder.append(item);
   builder.append("\n");
});
try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {
    writer.write(str);
}
// 第二种 
FileUtil.writeLines(list, tempFile, Charset.forName("UTF-8"));

字节流和字符流的输入输出

public class IOUtilsTest {
    @Test
    public void demo() {
        try (
                InputStream inputStream = new FileInputStream(new File("/Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/src/test/resources/a.txt"));
                FileOutputStream fileOutputStream = new FileOutputStream(new File("/Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/src/test/resources/b.txt"), true)
        ) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) != -1) {
//               write(b, off, len)的一般契约是数组b中的一些字节按顺序写入输出流;元素b[off]是写入的第一个字节,
//               b[off+len-1]是该操作写入的最后一个字节。
//               OutputStream的write方法在每个要写入的字节上调用一个参数的write方法
                fileOutputStream.write(buf, 0, len);
            }


        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void demo2(){
        File fileInput = new File("/Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/src/test/resources/a.txt");
        File fileOutput = new File("/Users/yyyyjinying/demo-file/git/backend/wx-project/wx-official-project/src/test/resources/c.txt");
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            fileReader = new FileReader(fileInput);
            fileWriter = new FileWriter(fileOutput);
            char[] buf = new char[1024];
            int len;
            while((len = fileReader.read(buf)) != -1){
                fileWriter.write(buf, 0, len);
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }


}

IOUtils.closeQuietly

可以简化io关闭的代码,

import org.apache.tomcat.util.http.fileupload.IOUtils;
import java.io.StringReader;
import java.io.StringWriter;
 try {
 
 } catch (IOException e) { 

 } finally {
       if (in != null) {
          try {
              in.close();
          } catch (IOException e) {
             
          }
       }
       if (out != null) {
          try {
              out.close();
          } catch (IOException e) {
             
          }
       }
 }       

 try {
 
 } catch (IOException e) { 

 } finally {
       IOUtils.closeQuietly(in);
       IOUtils.closeQuietly(out);
 }       
String content = "字符串";
StringReader reader = new StringReader(content);
StringWriter sw = new StringWriter();
try {
    //渲染模板 模板名没有取默认值
    String templateName = map.getOrDefault("templateName", "generator").toString();
    Template template = new Template(templateName, reader, null, "utf-8");
    template.process(map, sw);
} catch (Exception e) {
    e.printStackTrace();
    throw new RenException("渲染模板失败,请检查模板语法", e);
}

content = sw.toString();

IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(sw);
return content;

序列化和反序列化

序列化:将对象写入到IO流中,说的简单一点就是将内存模型的对象变成字节数字,可以进行存储和传输;
反序列化:从IO流中恢复对象,将存储在磁盘或者从网络接收的数据恢复成对象模型;
使用场景:所有可在网络上传输的对象都必须是可序列化的,否则会出错;所有需要保存到磁盘的Java对象都必须是可序列化的。
序列化版本号:我们知道,反序列化必须拥有class文件,但随着项目的升级,class文件也会升级,序列化怎么保证升级前后的兼容性呢?​ Java序列化提供了一个``private static final long serialVersionUID` 的序列化版本号,只要版本号相同,即使更改了序列化属性,对象也可以正确被反序列化回来。序列化版本号可自由指定,如果不指定,JVM会根据类信息自己计算一个版本号,这样随着class的升级、代码的修改等因素无法正确反序列化;不指定版本号另一个明显隐患是,不利于jvm间的移植,可能class文件没有更改,但不同jvm可能计算的规则不一样,这样也会导致无法反序列化。
所有需要网络传输的对象都需要实现序列化接口。
对象的类名、实例变量(包括基本类型,数组,对其他对象的引用)都会被序列化;方法、类变量、transient实例变量都不会被序列化。如果想让某个变量不被序列化,使用transient修饰。序列化对象的引用类型成员变量,也必须是可序列化的,否则,会报错。反序列化时必须有序列化对象的class文件。同一对象序列化多次,只有第一次序列化为二进制流,以后都只是保存序列化编号,不会重复序列化。建议所有可序列化的类加上serialVersionUID 版本号,方便项目升级。

/**
     * user对象通过字节流实现深拷贝
     * @throws CloneNotSupportedException
     */
    @Test
    public void deepClone() throws IOException, ClassNotFoundException {
        User user = new User("aa", "bb");
        user.setDog(new Dog("dog"));


        // 写出缓存字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
        out.writeObject(user);

        byte[] bytes = byteArrayOutputStream.toByteArray();

        // 将缓存字节数组写入程序对象
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream in = new ObjectInputStream(byteArrayInputStream);

        User user1 = (User) in.readObject();

// 关闭资源
        byteArrayInputStream.close();
        in.close();
        out.close();
        byteArrayOutputStream.close();




        user.setName("xiugai");
        user.getDog().setName("xigou");


        System.out.println(user);
        System.out.println(user1);
    }

    @Test
    public void qianClone() throws CloneNotSupportedException {
        User user = new User("aa", "bb");
        user.setDog(new Dog("dog"));


        User user1 = (User) user.clone();

        user.setName("xiugai");
        user.getDog().setName("xigou");


        System.out.println(user);
        System.out.println(user1);
    }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值