/*
字节流
InputStream
OutputStream
字节流缓冲区
BufferedInputStream
BufferedOutputStream
System.out:对应的是标准输出设备,控制台
System.in:对应的标准输入设备,键盘
InputStreamReader:字符流转换为字节流,字节流及其缓冲没有readLine方法,先变为字符流缓冲区
*/
package pack;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Main {
public static void sys(Object obj) {
System.out.println(obj);
}
public static void main(String[] args) throws IOException {
//method1();
//method2();
//method3();
//method4();
method5();
}
public static void method1() throws IOException {
FileOutputStream fos = new FileOutputStream("E:\\1.txt");
fos.write("abc".getBytes());//write方法里没有字符串参数,转换为字节数组
//字节流不需要刷新
fos.close();
}
public static void method2() throws IOException {
FileInputStream fis = new FileInputStream("E:\\1.txt");
/*int ch = 0;
while((ch=fis.read())!=-1) //一次读一个
sys((char)ch);
fis.close();*/
byte[] buf = new byte[fis.available()];//fis.available是个数
int len = 0;
while((len=fis.read(buf))!=-1)
sys(new String(buf,0,len));
fis.close();
}
/*拷贝图片,字节流*/
public static void method3() throws IOException {
FileOutputStream fos = new FileOutputStream("E:\\2.jpg");
FileInputStream fis = new FileInputStream("E:\\1.jpg");
int ch = 0;
while((ch=fis.read())!=-1)
fos.write(ch);
fos.close();
fis.close();
}
/*拷贝mp3,通过缓冲区*/
public static void method4() throws IOException {
BufferedOutputStream bufos=new BufferedOutputStream(new FileOutputStream("E:\\2.mp3"));
BufferedInputStream bufis=new BufferedInputStream(new FileInputStream("E:\\1.mp3"));
int ch = 0;
while((ch=bufis.read())!=-1)
bufos.write(ch);
bufis.close();
bufos.close();
}
public static void method5() throws IOException {
//字节流及其缓冲没有readLine方法,先变为字符流缓冲区
InputStream in = System.in; //获取键盘输入对象
InputStreamReader isr = new InputStreamReader(in);//字节流转换为字符流
BufferedReader bufr = new BufferedReader(isr); //字符流缓冲区
String line = null;
while((line=bufr.readLine())!=null) {
if(line.equals("over"))
break;
sys(line);
}
bufr.close();
}
}
时间: 2024-10-18 11:14:43