ByteArrayInputStream和ByteArrayOutputStream
//用ByteArrayOutputStream暂时缓存来自其他渠道的数据 ByteArrayOutputStream data = new ByteArrayOutputStream(1024); //1024字节大小的缓存区 data.write(System.in.read()); // 暂存用户输入数据 //将data转为ByteArrayInputStream ByteArrayInputStream in = new ByteArrayInputStream(data.toByteArray());
FileInputStream和FileOutputStream
ObjectInputStream和ObjectOutputStream
//java对象的写入 FileOutputStream fileStream = new FileOutputStream("example.txt"); ObjectOutputStream out = new ObjectOutputStream(fileStream); Example example = new Example(); out.writeObject(example); //java对象的读取 FileInputStream fileStream = new FileInputStream("example.txt"); ObjectInputStream in = new ObjectInputStream(fileStream); Example = (Example) in.readObject();
PipedInputStream和PipedOutputStream
// 创建一个发送者对象 Sender sender = new Sender(); // 创建一个接收者对象 Receiver receiver = new Receiver(); // 获取输出管道流 // 获取输入输出管道流 PipedOutputStream outputStream = sender.getOutputStream(); PipedInputStream inputStream = receiver.getInputStream(); // 链接两个管道,这一步很重要,把输入流和输出流联通起来 outputStream.connect(inputStream); sender.start();// 启动发送者线程 receiver.start();// 启动接收者线程
SequenceInputStream
InputStream in1 = new FileInputStream("example1.txt"); InputStream in2 = new FileInputStream("example2.txt"); SequenceInputStream sequenceInputStream = new SequenceInputStream(in1, in2); //数据读取 int data = sequenceInputStream.read();
ByteArrayOutputStream out = new ByteArrayOutputStream(2014); //数据写入,使用DataOutputStream装饰一个InputStream //使用InputStream具有对基本数据的处理能力 DataOutputStream dataOut = new DataOutputStream(out); dataOut.writeDouble(1.0); //数据读取 ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); DataInputStream dataIn = new DataInputStream(in); Double data = dataIn.readDouble();
DataInputStream和DataOutputStream (Filter流的子类)
BufferedInputStream和BufferedOutputStream (Filter流的子类)
PushBackInputStream (FilterInputStream子类)
PrintStream (FilterOutputStream子类)
//InputStream转为Reader InputStream inputStream = new ByteArrayInputStream("程序".getBytes()); InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); //OutputStream转为Writer OutputStream out = new FileOutputStream("example.txt"); OutputStreamWriter writer = new OutputStreamWriter(out); //以字符为单位读写 writer.write(reader.read(new char[2]));
两种出现乱码场景
ByteArrayInputStream in = new ByteArrayInputStream("程序大法好".getBytes()); byte[] buf = new byte[2]; //读取流的两个字节 in.read(buf); //读取数据 System.out.println(new String(buf)); //乱码 ---result---- � //乱码
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
范围 | Unicode(Binary) | UTF-8编码(Binary) | UTF-8编码byte长度 |
---|---|---|---|
U+0000~U+007F | 00000000 00000000 00000000 0XXXXXXX | 0XXXXXX | 1 |
U+0080~U+07FF | 00000000 00000000 00000YYY YYXXXXXX | 110YYYYY 10XXXXXX | 2 |
U+0800~U+FFFF | 00000000 00000000 ZZZZYYYY YYXXXXXX | 1110ZZZZ 10YYYYYY 10XXXXXX | 3 |
U+010000~U+10FFFF | 00000000 000AAAZZ ZZZZYYYY YYXXXXXX | 11110AAA 10ZZZZZZ 10YYYYYY 10XXXXXX | 4 |
System.out.println(Charset.defaultCharset()); //输出java默认编码 for (byte item : "程序".getBytes(StandardCharsets.UTF_16)) { System.out.print("[" + item + "]"); } System.out.println(""); for (byte item : "程序".getBytes(StandardCharsets.UTF_8)) { System.out.print("[" + item + "]"); } ----result---- UTF-8 //java默认编码UTF-8 [-2][-1][122][11][94][-113] //UTF_16:6个字节? [-25][-88][-117][-27][-70][-113] //UTF_8:6个字节 正常
for (byte item : "程".getBytes(StandardCharsets.UTF_16)) { System.out.print("[" + item + "]"); } ---result-- [-2][-1][122][11]
Uniform Resource Identifier
统一资源标识符URI 具有特定的规则: [scheme]:[scheme-specific-part][#fragment]
[scheme]:[//authority][/path][?query][#fragment]
,其中模式特定部分为authority和path、query;而authority可以看做域名,如www.baidu.com
[scheme]:[//host:port][/path][?query][#fragment]
,和日常见到的地址链接一毛一样了模式特定部分(scheme-specific-part)的形式取决于模式,而URI的常用模式如下
//根据str生成URI public URI(String str) throws URISyntaxException public URI(String scheme, String authority, String path, String query, String fragment)throws URISyntaxException public static URI create(String str) //调用 URI(String str)
public String getScheme() //获取模式 public String getSchemeSpecificPart()//获取模式特定部分 public String getFragment() //获取片段标识符 //以上三个方法是通用的 public String getAuthority() //授权机构,如www.baidu.com public String getHost() //获取主机部分,如127.0.0.1 public int getPort() //如8080 public String getPath() //定位路径 public String getQuery() //查询条件
Uniform Resource Location
,统一资源定位符mailto:clswcl@gmail.com
就是一种URN,知道这是个邮箱,却不知道该怎么查找定位协议://主机名:端口/路径?查询#片段 [protocol]:[//host:port][/path][?query][#fragment]
//基于URL模式构造URL实例 public URL(String spec) throws MalformedURLException //其中file相当于path、query和fragment三个部分组成 public URL(String protocol, String host, int port, String file) throws MalformedURLException //根据类加载器获取URL URL systemResource = ClassLoader.getSystemResource(String name) Enumeration<URL> systemResources = ClassLoader.getSystemResources(String name) URL resource = Main.class.getResource(String name) Enumeration<URL> resources = Main.class.getClassLoader().getResources(String name)
public final InputStream openStream() throws java.io.IOException public URLConnection openConnection() throws java.io.IOException public final Object getContent() throws java.io.IOException
讲到资源,就得提下Spring获取资源方式,常用的有两种
Resource resource = new FileSystemResource("D:/example.txt"); File file= new File("example.txt"); Resource resource2 = new FileSystemResource(file);
2 ByteArrayResource:获取byte数组表示的资源
//ClassPathResource.java 的三个属性 private final String path; //使用Class或ClassLoader加载资源 private ClassLoader classLoader; private Class<?> clazz; ---使用方式---- Resource resource = new ClassPathResource("test.txt");
public interface ResourceLoader { // 默认从类路径加载的资源 前缀: "classpath:",获取ClassPathResource String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX; Resource getResource(String location);
public interface ResourcePatternResolver extends ResourceLoader { // 默认加载所有路径(包括jar包)下面的文件,"classpath*:", 获取ClassPathResource String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
//Ant风格表达式 com/smart/**/*.xml ResourcePatternResoler resolver = new PathMatchingResourcePatternResolver(); Resource resources[] = resolver.getResources("com/smart/**/*.xml"); // ApplicationContext ctx //FileSystemResource资源 Resource template = ctx.getResource("file:///res.txt"); //UrlResource资源 Resource template = ctx.getResource("https://my.cn/res.txt");
前缀 | 示例 | 描述 |
---|---|---|
classpath: | classpath:config.xml | 从类路径加载 |
file: | file:///res.txt | 从文件系统加载FileSystemResource |
http: | http://my.cn/res.txt | 加载UrlResource |
public class Properties extends Hashtable<Object,Object>{ .... //可根据Reader或者InputStream加载properties文件内容 public synchronized void load(Reader reader) throws IOException public synchronized void load(InputStream inStream) throws IOException
//res.properties username = root password = password -------代码示例------------- InputStream input = ClassLoader.getSystemResourceAsStream("res.properties"); Properties prop = new Properties(); prop.load(inputStream); //根据inputStream载入资源 String username = prop.getProperty("username");
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.9.5</version> </dependency>
//res.yml 配置 name: chen params: url: http://www.my.com ----------代码示例--------------- InputStream input = ClassLoader.getSystemResourceAsStream("res.yml"); Yaml yml = new Yaml(); Map map = new Yaml().loadAs(input, LinkedHashMap.class);; //根据inputStream载入资源 String name = MapUtils.getString(map,"name"); // chen //url: http://www.my.com String url = MapUtils.getString((Map)map.get("params"),"url")
public class YSOAPConnection implements AutoCloseable { private SOAPConnection connection; public static YSOAPConnection open(SOAPConnectionFactory soapConnectionFactory) throws SOAPException { YSOAPConnection ySoapConnection = new YSOAPConnection(); SOAPConnection connection = soapConnectionFactory.createConnection(); ySoapConnection.setConnection(connection); return ySoapConnection; } public SOAPMessage call(SOAPMessage request, Object to) throws SOAPException { return connection.call(request, to); } @Override public void close() throws SOAPException { if (connection != null) { connection.close(); } } }
//自动关闭的资源类使用示例 try (YSOAPConnection soapConnection=YSOAPConnection.open(soapConnectionFactory)){ SOAPMessage soapResponse = soapConnection.call(request, endpoint); ...//数据操作 } catch (Exception e) { log.error(e.getMessage(), e); ... }
public void close()
;对象需实现AutoCloseable接口import lombok.Cleanup; @Cleanup // @Cleanup的使用 YSOAPConnection soapConnection=YSOAPConnection.open(soapConnectionFactory)
//FileInputStream.java - JDK8 //jdk8的FileInputStream重写了finalize,保证对象回收前开启的资源被关闭 protected void finalize () throws IOException { if (guard != null) { guard.warnIfOpen(); } if ((fd != null) && (fd != FileDescriptor.in)) { close(); } }