2017-03-08 255 views
2

有一種方法可以將inputStream轉換爲String,並將其編碼爲base64? 在我的函數我得到InputStream參數,並需要將其插入到我的DB-oracle BLOB字段有一種方法來做到這一點? (我的對象包含字符串字段來保存圖像裏面,但我沒有找到任何方式將inputStream轉換爲以base64格式的字符串) 謝謝!java將inputStream轉換爲base64字符串

+0

你嘗試過什麼嗎?如果您的InputStream包含圖像數據,請不要使用「String」,而應使用「byte []''。 – f1sh

+0

好的,這是什麼意思?我需要將此字段更改爲字節[]?以及如何將它從inputStream轉換爲Byte []?謝謝! – foo

回答

5

你可以使用Base64 API來嘗試這樣的事情。

InputStream finput = new FileInputStream(file); 
byte[] imageBytes = new byte[(int)file.length()]; 
finput.read(imageBytes, 0, imageBytes.length); 
finput.close(); 
String imageStr = Base64.encodeBase64String(imageBytes); 

使用此:

http://commons.apache.org/proper/commons-codec/archives/1.9/apidocs/org/apache/commons/codec/binary/Base64.html

+0

新的FileInputStream需要獲取文件 - 我沒有文件名....我需要設置inputStream .... – foo

+0

,只要您有InputStream,就應該可以。你使用提到的邏輯 – mhasan

+0

Base64.DEFAULT - 得到編譯錯誤 - DEFAULT不是字段。我需要做什麼? – foo

1

最簡單的方法是使用IOUtils從Apache的公地做到這一點:

String result= IOUtils.toString(inputStream, ENCODING); 

從文檔:

的toString(字節[]輸入,字符串編碼) 獲取一個byte []的內容作爲一個字符串,使用指定的字符編碼。

之後編碼/解碼爲Base64:

// Encode 
String resultBase64Encoded = Base64.getEncoder().encodeToString(result.getBytes("utf-8")); 


// Decode 
byte[] asBytes = Base64.getDecoder().decode(resultBase64Encoded); 
String resultAsStringAgain= String(asBytes, "utf-8") 

注:我假設你使用JDK 8的編碼/解碼部分。

顯然,OP只想將InputStream保存到數據庫中。你可以直接使用JDBC來做到這一點:

InputStream inputStream = ......; 
String sql = "INSERT INTO TABLE_NAME(COLUMN_NAME) values (?)"; 
PreparedStatement statement = connection.prepareStatement(sql); 
statement.setBlob(1, inputStream); 
statement.executeUpdate(); 
+0

將二進制數據讀取到''String''不是一個好主意。 – f1sh

+0

@ f1sh我知道,但這是OP要求的。 – Alboz

+0

那我該怎麼辦?在將圖像數據插入數據庫blob之前,我應該在哪裏放置圖像數據? – foo

1

正如我提到的,你不應該使用String二進制數據。儘管base64編碼的數據可以存儲爲字符串。但是由於你的數據庫列是一個blob,我會繼續使用byte[]

使用IOUtils來從InputStream一個byte[]

byte[] bytes = IOUtils.toByteArray(yourInputStream); 
byte[] encoded = java.util.Base64.getEncoder().encode(bytes); 

然後將其寫入到數據庫中。使用JDBC寫BLOB和一個PreparedStatement看起來是這樣的:

yourPreparedStatement.setBytes(nIndex, encoded); 
+0

我需要添加哪些進口? – foo

2

有很好的辦法做到這一點是使用IOUtils到的InputStream轉換爲Byte Array ...

InputStream is; 
    byte[] bytes = IOUtils.toByteArray(is); 

在這裏您可以使用Base64Byte Array轉換爲String

示例代碼

String encoded = Base64.getEncoder().encodeToString(bytes); 

現在你可以使用你的String