字节流
1. InputStream 字节输入流
代码演示
InputStream in = System.in; System.out.println("int read(byte b) 方法演示");
//int read()
int bt = 0;
while((bt=in.read())>0){
System.out.print(bt+" ");
if(bt == 10){ //回车\r(13) 换行\n(10)
break;
}
}
System.out.println("\n\rint read(byte[] buffer) 方法演示"); //int read(byte[] buffer)
int length = 0;
byte[] buffer = new byte[10];
while((length=in.read(buffer)) != 0){
for(int i=0; i<length; i++){
System.out.print(buffer[i]+" ");
}
break;
} System.out.println("\n\rint read(byte[] buffer, int offset, int len) 方法演示"); //int read(byte[] buffer, int offset, int len)
int len = 1024;
int count = 0;
byte[] buf = new byte[len];
while((count=in.read(buf, 0, len))>0){
for(int i=0; i<count; i++){
System.out.print(buf[i]+" ");
}
break;
}
in.close();
2. OutputStream 字节输出流
代码演示
OutputStream out = System.out;
//void write(int b)
out.write(65); //字符A out.write(13); //回车 \r
out.write(10); //换行 \n //flush()
out.flush(); //write(byte[] bytes)
byte[] bytes = new String("张晓明").getBytes();
out.write(bytes); out.write(13); //回车 \r
out.write(10); //换行 \n //write(byte[] bytes, int offset, int length)
bytes = new String("zhangxiaoming").getBytes();
out.write(bytes, 5, 8); out.close();
字符流
1. Reader 字符输入流
代码演示
Reader reader = new InputStreamReader(System.in); //int read()
System.out.println("int read() 方法演示");
int c;
while((c=reader.read()) != 13){
System.out.print((char)c);
}
reader.read(); //int read(char[] buf)
System.out.println("\n\rint read(char[] buf) 方法演示");
int count = 0;
char[] buf = new char[1024];
while((count=reader.read(buf)) > 0){
String str = new String(buf, 0, count);
if(str.indexOf("stop")>=0) break;
System.out.print(str);
} //int read(char[] buffer, int offset, int len)
System.out.println("\n\rint read(char[] buffer, int offset, int len) 方法演示");
int length = 1024;
char[] buffer = new char[length];
while((count=reader.read(buffer, 0, length)) > 0){
String str = new String(buffer, 0, count);
if(str.indexOf("stop")>=0) break;
System.out.print(str);
}
2. Writer 字符输出流
代码演示
Writer writer = new OutputStreamWriter(System.out);
String str = "中国"; //write(String str) 写入字符串
writer.write(str); //write(int c) 写入单个字符
writer.write(10); //换行符 //write(String str, int offset, int length) 写入部分字符串
writer.write(str, 0, 1); writer.write(10); //write(char[] buf) 写入字符数组
char[] chars = str.toCharArray();
writer.write(chars); writer.write(10); //write(char[] buf, int offset, int length) 写入部分字符数组
writer.write(chars, 0, 1);
writer.write(10); writer.flush(); //append(char c) 追加字符
writer.append('z');
writer.write(10); String str2 = "中华人民共和国";
//append(CharSequence csq)
writer.append(str2);
writer.write(10); //append(CharSequence csq, int offset, int length)
writer.append(str2, 0, 4); writer.close();