Trong bài viết này, chúng ta sẽ tìm hiểu cách chuyển đổi chuỗi (String) thành InputStream. String là kiểu dữ liệu chứa một hoặc nhiều ký tự, bao quanh bởi dấu nháy kép. InputStream là lớp cha của tất cả các lớp đại diện cho luồng đầu vào byte.
Ví dụ minh họa
Đầu vào:
Chuỗi đầu vào: Java Program
Đầu ra mong muốn:
Số byte có sẵn ban đầu: 12 Số byte có sẵn sau khi đọc: 10
Thuật toán
- Bắt đầu
- Khai báo chuỗi
input_stringvà đối tượng InputStreaminput_stream - Gán giá trị
- Sử dụng
read()để đọc byte và.available()để lấy byte còn lại - Hiển thị kết quả
- Kết thúc
Ví dụ 1: Xử lý trực tiếp trong main
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class Demo {
public static void main(String args[]) {
String input_string = "Java Program";
System.out.println("Chuỗi được định nghĩa: " + input_string);
try {
InputStream input_stream = new ByteArrayInputStream(input_string.getBytes(StandardCharsets.UTF_8));
System.out.println("Số byte có sẵn ban đầu: " + input_stream.available());
input_stream.read();
input_stream.read();
System.out.println("Số byte có sẵn sau khi đọc: " + input_stream.available());
input_stream.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
Kết quả
Chuỗi được định nghĩa: Java Program Số byte có sẵn ban đầu: 12 Số byte có sẵn sau khi đọc: 10
Ví dụ 2: Sử dụng phương thức tách biệt (OOP)
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class Demo {
static void check_bytes(String input_string) {
try {
InputStream input_stream = new ByteArrayInputStream(input_string.getBytes(StandardCharsets.UTF_8));
System.out.println("Số byte có sẵn ban đầu: " + input_stream.available());
input_stream.read();
input_stream.read();
System.out.println("Số byte có sẵn sau khi đọc: " + input_stream.available());
input_stream.close();
} catch (Exception e) {
e.getStackTrace();
}
}
public static void main(String args[]) {
String input_string = "Java Program";
System.out.println("Chuỗi được định nghĩa: " + input_string);
check_bytes(input_string);
}
}
Kết quả
Chuỗi được định nghĩa: Java Program Số byte có sẵn ban đầu: 12 Số byte có sẵn sau khi đọc: 10