Java如何将byte[]数据转化为string类型
时间: 2023-04-01 16:01:10 浏览: 68
Java中可以使用String类的构造函数将byte[]数据转化为string类型,具体代码如下:
byte[] bytes = {97, 98, 99, 100};
String str = new String(bytes);
System.out.println(str);
输出结果为:abcd
相关问题
java将byte数组转化为json
要将byte数组转换为JSON,需要先将byte数组转换为字符串,然后使用JSON库将其转换为JSON格式。下面是一个示例:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class ByteToJson {
public static void main(String[] args) throws IOException {
byte[] bytes = {1, 2, 3, 4, 5};
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(bytes);
System.out.println(jsonString);
}
}
```
输出结果:
```
[1,2,3,4,5]
```
在上面的示例中,我们使用了Jackson库的ObjectMapper类将byte数组转换为JSON格式的字符串。注意,这里我们将byte数组转换为一个JSON数组,因为JSON没有专门的byte类型。
利用java代码将mysql的blob转化为String类型
可以使用以下代码把 MySQL 的 blob 转成字符串:
```
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
ps = conn.prepareStatement("SELECT content FROM mytable WHERE id = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("content");
byte[] bytes = blob.getBytes(1, (int) blob.length());
String content = new String(bytes, "UTF-8");
System.out.println(content);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
```