字节流
InputStream
FileInputStream fis = newFileInputStream("demo.txt");
1.
byte[]b = new byte[fis.available];
fis.read(b);
System.out.println(newString(b));
2.
byte[]buf = new byte[1024];
intlen = 0;
while((len=fis.read(buf))!=-1){
System.out.println(newString(buf,0,len));
}
3.
intlen = 0;
while((len=fis.read())!=-1){
System.out.println((char)len);
}
OutputStream
FileOutputStrdamfos = newFileOutputStream("demo.txt");
fos.write("aabadsd".getBytes());//不用手动刷新,自动刷新
fos.close():
文件拷贝
publicstatic void main(String[] args) throws IOException {
Stringsrc = "D:\\love.mp3";
Stringdes = "E:\\my.mp3";
copyMedio(src,des);
copyMedio1(src,des);
}
public static void copyMedio1(String src, Stringdes) throws IOException {
FileInputStreamfis = new FileInputStream(src);
BufferedInputStreambuffis = new BufferedInputStream(fis);
FileOutputStreamfos = new FileOutputStream(des);
BufferedOutputStreambos = new BufferedOutputStream(fos);
// byte[] buf = new byte[BUF_SIZE];
intlen = 0;
while((len= buffis.read())!=-1){
fos.write(len);
}
System.out.println("拷贝成功");
fos.close();
fis.close();
}
privatestatic void copyMedio(String src, String des) throws IOException {
FileInputStreamfis = new FileInputStream(src);
FileOutputStreamfos = new FileOutputStream(des);
byte[]buf = new byte[BUF_SIZE];
intlen = 0;
while((len= fis.read(buf))!=-1){
fos.write(buf,0, len);
}
System.out.println("拷贝成功");
fos.close();
fis.close();
}
从键盘读取数据到控制台
publicstatic void main(String[] args) throws IOException {
InputStreaminput = System.in;//通过系统类获取类中的静态输入流对象
Stringdesc = "D:\\t1.txt";//键盘录入的输入流不能手动关,因为就有一个
//这样的流。关掉后,就创建不了了
KeyWrite(desc,input);
//输入流的read方法等待输入,处于阻塞状态
}
publicstatic void KeyWrite(String desc, InputStream input) throws IOException {
BufferedInputStreambis = new BufferedInputStream(input);
BufferedWriterbos = new BufferedWriter(new FileWriter(desc,true));
byte[]b = new byte[1024];
intlen = 0;
while((len= bis.read(b))!=-1){
bos.write(newString(b,0,len));
bos.flush();
}
bos.close();
}