一、inputstream轉map
在inputstream轉outputstream之前,我們可以先介紹一下如何將inputstream轉換成map。因為有時候我們需要將inputstream中的內容轉化為map類型進行處理。
public static Map inputStream2Map(InputStream inputStream) throws IOException{ BufferedReader bf=new BufferedReader(new InputStreamReader(inputStream)); String line; Map map=new HashMap(); while((line = bf.readLine())!=null){ String[] s = line.split("="); if(s.length==2){ map.put(s[0], s[1]); } } bf.close(); return map; }
上述方法將一個inputstream轉化為一個由鍵值對映射組成的map,並且將鍵值對兩者使用“=”分隔。這個方法不僅可以將inputstream轉化為map,如果我們忽略掉“=”分隔,則可以將inputstream中的內容作為一個字符串輸出。
二、inputstream讀取
在inputstream轉outputstream之前,我們需要了解如何從inputstream中讀取數據。
public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, len); } byteArrayOutputStream.close(); return byteArrayOutputStream.toByteArray(); }
上面這個方法可以將inputstream中的數據讀取到一個buffer中,並且將buffer中的內容寫到ByteArrayOutputStream中,最後以byte數組的形式返回。
三、outputstream轉文件
在inputstream轉outputstream中,我們也需要將outputstream中的數據轉化為文件。下面這個方法可以將outputstream中的數據寫入到一個文件中,並且返迴文件路徑。
public static String writeOutputStreamToFile(OutputStream outputStream, String folderPath, String fileName) throws IOException { String filePath = folderPath + File.separator + fileName; File folder = new File(folderPath); if (!folder.exists()) { folder.mkdirs(); } File file = new File(filePath); if (file.exists()) { file.delete(); } file.createNewFile(); OutputStream fileOutputStream = new FileOutputStream(file); outputStream.writeTo(fileOutputStream); outputStream.close(); fileOutputStream.close(); return filePath; }
上述方法將outputstream中的數據寫入到文件中並且返回一個文件路徑,在使用的時候需要傳進兩個參數,一個是文件目錄的路徑,第二個是保存到文件中的名字。使用這個方法可以方便地將outputstream轉化成文件,也為outputstream寫入到數據庫中提供了一個思路。
四、inputstream是什麼流
我們在前面已經介紹了如何讀取和轉換inputstream,但是對於inputstream來說,到底是什麼流呢?Inputstream是java內部提供的使用非常廣泛的一個數據輸入流,可以從不同的數據源中輸入數據,例如文件、網絡、socket等等。在使用的時候,需要給這個流提供一個數據源,然後從流中不斷讀取數據進行操作。
五、outputstream用法
outputstream和inputstream是一對的。outputstream是一個數據輸出流,在java中同樣非常常用。outputstream可以將數據輸出到不同的地方,例如保存到文件、網絡、socket等等。在使用的時候,同樣需要給outputstream提供一個數據來源,並不斷向流中寫入數據。
public static void writeToOutputStream(OutputStream outputStream, String content) throws IOException { outputStream.write(content.getBytes()); outputStream.flush(); outputStream.close(); }
可以使用上述方法將字符串寫入到outputstream中。在使用的時候,需要給這個方法傳入兩個參數,一個是outputstream,第二個是需要寫入的字符串。
六、inputstream作用
inputstream是一個非常常用的流,因為在java中,很多物理資源都以inputstream的方式提供給程序進行操作。例如文件、網絡、socket等等,都可以使用inputstream來進行讀取和操作。inputstream的使用非常廣泛,因此深入掌握和理解inputstream對於Java開發者來說非常重要。
七、總結
本文對於inputstream轉outputstream進行了詳細的闡述,分別從inputstream轉map、inputstream讀取、outputstream轉文件、inputstream是什麼流、outputstream用法、inputstream作用等多個方面進行了說明。每個方面都詳細闡述了使用的方法和步驟,對於需要進行inputstream轉outputstream操作的開發者來說非常有幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/152501.html