Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

java - 如何在Java中将字符串转换为InputStream? [重复](How do I convert a String to an InputStream in Java? [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

Given a string:

(给定一个字符串:)

String exampleString = "example";

How do I convert it to an InputStream ?

(如何将其转换为InputStream ?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Like this:

(像这样:)

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8 .

(请注意,这假设您需要一个InputStream,它是一个字节流,它表示编码为UTF-8的原始字符串。)

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8" .

(对于Java版本少于7的版本,将StandardCharsets.UTF_8替换为"UTF-8" 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...