การแปลง String เป็น InputStream ใน Java

ต่อไปนี้คือตัวอย่างง่ายๆสำหรับการการแปลง String เป็น InputStream โดยใช้ BufferedReader เพื่ออ่านข้อมูลมาแสดงครับ.
ตัวอย่าง
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package demo.file;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class StringToInputStreamExample {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        String str = "This is a string to InputStream example";
 
        // convert String into InputStream
        InputStream is = new ByteArrayInputStream(str.getBytes());
        // read it with BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        try {
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
         
        br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
ผลลัพธ์ที่ได้คือ
1
This is a string to InputStream example

About Nop

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment