ByteArrayInputStream和ByteArrayOutputStreamhtml
//用ByteArrayOutputStream暫時緩存來自其餘渠道的數據 ByteArrayOutputStream data = new ByteArrayOutputStream(1024); //1024字節大小的緩存區 data.write(System.in.read()); // 暫存用戶輸入數據 //將data轉爲ByteArrayInputStream ByteArrayInputStream in = new ByteArrayInputStream(data.toByteArray());
FileInputStream和FileOutputStreamjava
ObjectInputStream和ObjectOutputStreamlinux
//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和PipedOutputStreamandroid
// 建立一個發送者對象 Sender sender = new Sender(); // 建立一個接收者對象 Receiver receiver = new Receiver(); // 獲取輸出管道流 // 獲取輸入輸出管道流 PipedOutputStream outputStream = sender.getOutputStream(); PipedInputStream inputStream = receiver.getInputStream(); // 連接兩個管道,這一步很重要,把輸入流和輸出流聯通起來 outputStream.connect(inputStream); sender.start();// 啓動發送者線程 receiver.start();// 啓動接收者線程
SequenceInputStreamspring
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子類)springboot
//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(); } }