- public class StreamFromString {
- static String src = "今天的天气真的不好";
- public static void main(String[] args) throws IOException {
- byte[] buff = new byte[1024];
- //从字符串获取字节写入流
- InputStream is = new ByteArrayInputStream(src.getBytes("utf-8"));
- int len = -1;
- while(-1 != (len = is.read(buff))) {
- //将字节数组转换为字符串
- String res = new String(buff, 0, len);
- System.out.println(res);
- }
- }
- }
文本文件里字节流的长度即为文件的长度:
String src = "今天的天气真的不好";
int k = 0;
InputStream in = new ByteArrayInputStream(src.getBytes("GBK"));
File f = new File("G:\\test.txt");
int l = (int)f.length();
System.out.println("字符串的长度"+src.length());
System.out.println("文件长度"+l);
try {
while(in.read()!=-1)
k++;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("字节流长度"+k);
java字符串转换成字节流
最新推荐文章于 2021-11-20 17:31:04 发布