黑马程序员----IO流(一)

------- android培训java培训、期待与您交流! ----------

一、File类

File类:文件和目录路径名的抽象表示形式。

File类的方法:

long length()  获取File构造方法中封装的文件的字节数。

long lastModified()  获取File构造方法中封装的文件的最后修改时间的毫秒值。

File getParentFile()  获取构造方法中封装的路径的父路径,返回值是File对象。

String getParent()  获取父路径。获取构造方法中封装的路径的父路径。

String getPath   将构造方法中封装的路径,转成一个字符串。

String[] list()  File构造方法,写的路径,获取路径下的文件和文件夹。

File[] listFiles()  File构造方法,写的路径,获取路径下的文件和文件夹。返回File数组,获取全路径。

listFiles(FileFilter filter)  传递参数,参数就是文件过滤器,参数FileFilter接口,java.io.FileFilter。传递实现类,自己写实现类,实现接口,重写方法 boolean accept(File pathname) 

class myFilter implements FileFilter{
//在File类的 listFiles方法中,被调用的
//传递参数pathname,结果就是listFiles()获取到的全路径
//接收路径pathname,当方法返回的是真,路径装到集合中
//文件名是.java文件返回真
public boolean accept(File pathname){
//判断传递参数pathname的文件名后缀是不是.java,如果是就返回true
return pathname.getName().endsWith(".java");
// return true;
}
}
public class FileDemo2{
public static void main(String[] args) {
File file = new File("c:\\demo");
File[] files = file.listFiles( new myFilter());
for(File f : files){
System.out.println(f);
}
}
}

二、IO流

IO流用来处理设备之间的数据传输。
java对数据的操作时通过流的方式。
java用于操作流的对象都在IO包中。
流按操作数据分为两种:字节流与字符流。
流按流向分为:输入流,输出流。
IO常用基类
字节流的抽象基类:InputStream,OutputStream
字符流的抽象基类:Reader,Writer


数据的最常见体现形式是文件

字符流缓冲区
缓冲区的出现提高了对数据读写的效率。
对应类:BufferedReader
              BurreredWriter
缓冲区要对应流才能使用。
在流的基础上对流功能进行增强。
装饰类通常会通过构造方法接收被装饰对象,并基于被装饰对象的功能提供更强的功能。

字符流:Reader,Writer
        FileReader
FileWriter
BufferedReader
BufferedWriter


字节流:InputStream
      OutputStream
              FileInputStream  将数据读取到流中  都是相对于程序而言。
              FileOutputSteam  将数据写入到文件
转换器:InputStreamReader  OutputStreamWriter

流操作的基本规律:
1)明确源和目的
     源:输入流InputStream  Reader
目的:输出流 OutputStream Writer
2)明确操作的数据是否是纯文本。
      是:Reader Writer
 否:InputStream OutputStream
3) 当体系明确后,再明确具体要使用哪个对象。
  通过设备来区分
  设备:内存,硬盘,控制台,键盘.

1、FileWrite

import java.io.*;
class FileWriterDemo {
public static void main(String[] args) {
try{
FileWriter fw = new FileWriter("aaa.txt");
//必须指定要操作的文件。
//将文件创建到制定目录下,如果文件存在,则被覆盖。
fw.write("asdf");
//调用write方法,将字符串写入到流中。
fw.flush();
//刷新流对象中的缓冲数据,将数据刷到目的地中。
fw.write("123");
fw.flush();
fw
.close();

}catch (IOException e){
System.out.println(e.toString());}
}
}

2、IOException处理

import java.io.*;
class FileWriterDemo2 {
public static void main(String[] args) {
FileWriter fw = null;
try{
fw = new FileWriter("aaa.txt");
//必须指定要操作的文件。
//将文件创建到制定目录下,如果文件存在,则被覆盖。
fw.write("asdf");
//调用write方法,将字符串写入到流中。
fw.flush();
//刷新流对象中的缓冲数据,将数据刷到目的地中。
fw.write("123");
fw.flush();
//fw.close();
//刷新并关闭流。
}catch (IOException e){
System.out.println(e.toString());
}finally{
try{
if(fw!=null)
fw.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
}

3、文件续写

import java.io.*;
class FileWriterDemo3 {
public static void main(String[] args) {
FileWriter fw = null;
try{
fw = new FileWriter("aaa.txt",true);
//传递true参数代表不覆盖已有文件,并在已有文件的末尾处追加内容。
fw.write("\r\n");
fw.write("another line");
fw.flush();
}catch (IOException e){
System.out.println(e.toString());
}finally{
try{
if(fw!=null)
fw.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
}

4、读取文件1


import java.io.*;
class FileReaderDemo{
public static void main(String[] args){
FileReader fr = null;
try{
//创建一个文件读取流对象,文件不存在时,抛出FileNotFoundException异常
fr =new FileReader("ttt.txt");
char temp =(char)fr.read();//此方法读取到结尾时返回-1;
System.out.println(temp);
int ch = 0;
while((ch=fr.read())!=-1){
System.out.println((char)ch);
}
}catch (IOException e){
System.out.println(e.toString());
}finally{
try
{
if(fr!=null)
fr.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
}

5、读取方式2


import java.io.*;
class FileReaderDemo2{
public static void main(String[] args)throws IOException{
FileReader fr = new FileReader("aaa.txt");
int temp = 0;
char[] ch = new char[1024];
while((temp=fr.read(ch))!= -1){
System.out.println("....."+new String(ch,0,temp)+"......");
}
fr.close();
}
}

6、将文本文件打印到终端。


import java.io.*;


class FileReaderTest{
public static void main(String[] args){
printFile("CalendarDemo.java");
}
public static void printFile(String target){
FileReader fr = null;
int temp =0;
char[] ch = new char[1024];
try{
fr = new FileReader(target);
while((temp = fr.read(ch))!=-1){
System.out.print(new String(ch,0,temp));
}
}catch (IOException e){
System.out.println(e.toString());
}finally{
try{
if(fr!=null)
fr.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
}

7、将指定文件复制到指定目录。


import java.io.*;
class CopyFileDemo{
public static void main(String[] args){
copyFile("FileWriterDemo.java","D:\\test.java");
}
public static void copyFile(String res,String des){
FileWriter fw = null;
FileReader fr = null;
char[] ch = new char[1024];
int temp = 0;
try{
fr = new FileReader(res);
fw = new FileWriter(des);
while((temp=fr.read(ch))!=-1){
fw.write(ch,0,temp);
fw.flush();//刷流
}
}catch (IOException e){
System.out.println(e.toString());
throw new RuntimeException();
}finally{
if(fr!=null){
try{
fr.close();
}catch (IOException e){
System.out.println(e.toString());
}finally{
if(fw!=null)
try{
fw.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
}
}
}

8、写入字符流缓冲区BufferedWriter.


import java.io.*;
class BufferedWriterDemo{
public static void main(String[] args)throws IOException{
//创建文件写入字符流对象
FileWriter fw = new FileWriter("aaa.txt");
//将流传给给缓冲区构造函数。
BufferedWriter bfrt = new BufferedWriter(fw);
bfrt.write("asdfasdfasdfasdf");
bfrt.newLine();//跨平台换行方法。
bfrt.write("asdfasdfasdfasdf");
bfrt.flush();
bfrt.close();//关闭流。
}
}

9、读取字符流缓冲区BufferedReader
readLine返回的串不包含回车符。
readLine方法原理:
无论是读一行,或者读取多个字符,最终都是在硬盘上一个一个的读取,所以最终使用的还是read方法一次读取一个。


import java.io.*;
class BufferedReaderDemo{
public static void main(String[] args)throws IOException{
BufferedReader bfrd = new BufferedReader(new FileReader("aaa.txt"));

String s = null;
while((s=bfrd.readLine())!=null){//一次读取一行,BufferedReader特有方法。
System.out.println(s);
}
bfrd.close();
}
}

10、使用缓冲区复制文件。


import java.io.*;
class CopyFileWithBuffered
{
public static void main(String[] agrs)
{
copyFileByBuffered("CalendarDemo.java","D:\\test.txt");
}
public static void copyFileByBuffered(String res,String des)
{
BufferedReader br = null;
BufferedWriter bw = null;
try
{
br = new BufferedReader(new FileReader(res));
bw = new BufferedWriter(new FileWriter(des));
}
catch (IOException e)
{
System.out.println(e.toString());
throw new RuntimeException();
}
try
{
String s = null;
int x = 0;
while((s=br.readLine())!=null)//readLine返回的串不包含回车符。
{
bw.write(s);
bw.newLine();
x++;
if(x%5==0)
bw.flush();
}
bw.flush();
}
catch (IOException e)
{
throw new RuntimeException("读取或写入失败");
}
finally
{
if(br!=null)
try
{
br.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
   finally
   {
if(bw!=null)
try
{
bw.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
}
}
}
}

11、明白了BufferedReader类中特有方法readLine的原理后
自定义一个类中包含一个功能和readLine一致的方法。


装饰设计模式:
想要对已有对象进行功能增强时。
可以自定义类,将已有对象传入,基于已有功能,并提供增强功能。
自定义的该类就称为装饰类。
装饰模式比继承灵活,避免了继承体系的臃肿。并且降低了类与类之间的关系。


因为装饰类增强已有对象,具备的功能和已有功能是相同的,只不过提供了增强功能。
所以装饰类和别装饰类通常处于同一体系中。


import java.io.*;
class MyBufferedReaderDemo
{
public static void main(String[] args)throws IOException
{
FileReader fr = new FileReader("aaa.txt");
MyBufferedReader mbr = new MyBufferedReader(fr);
String s = null;
while((s=mbr.myReadLine())!=null)
{
System.out.println(s);
}
mbr.myClose();
}
}
class MyBufferedReader extends Reader
{
private Reader r;
MyBufferedReader(Reader r)
{
this.r =r;
}
public String myReadLine()throws IOException//定义一个和readLine方法功能一致的方法。
{
//定义一个临时容器存储独到的字符。
StringBuilder sb = new StringBuilder();
int temp = 0;
while((temp=r.read())!=-1)
{
if(temp=='\r')
continue;
if(temp=='\n')
return sb.toString();
sb.append((char)temp);
}
if(sb.length()!=0)
return sb.toString();
return null;
}
public void close()throws IOException
{
r.close();
}
public int read(char[] cbuf,int off,int len)throws IOException
{
return r.read(cbuf,off,len);
}
public void myClose()throws IOException
{
r.close();
}
}
---------------------------------------------------------------------------------
LineNumberReader
int getLineNumber();
void setLineNumber(int lineNumber);


import java.io.*;
class LineNumberReaderDemo
{
public static void main(String[] args)throws IOException
{
LineNumberReader lnr = new LineNumberReader(new FileReader("BufferedReaderDemo.java"));
String s = null;
lnr.setLineNumber(100);//行号从一百开始
while((s=lnr.readLine())!=null)
{
int line = lnr.getLineNumber();//获取行号。
System.out.println(line+":"+s);
}
lnr.close();
}
}

12、字节流
操作图片数据,需要使用字节流。
InputStream
OutputStream


import java.io.*;
class FileStreamDemo
{
public static void main(String[] args)throws IOException
{
FileWrite();
FileRead_1();
FileRead_2();
FileRead_3();
}
public static void FileWrite()throws IOException
{
FileOutputStream os = new FileOutputStream("data.txt");
os.write("asdf".getBytes());//没有缓冲,不需刷新。
os.close();
}
public static void FileRead_1()throws IOException
{
FileInputStream is = new FileInputStream("data.txt");
int num = 0;
while((num=is.read())!=-1)
{
System.out.println((char)num);
}
is.close();
}
public static void FileRead_2()throws IOException
{
FileInputStream is = new FileInputStream("data.txt");
byte[] buf = new byte[1024];
int len = 0;
while((len = is.read(buf))!=-1)
{
System.out.println(new String(buf,0,len));
}


is.close();
}
public static void FileRead_3()throws IOException//小文件可以使用该方法,大文件可能导致内存溢出。
{
FileInputStream is = new FileInputStream("data.txt");
int num = is.available();
byte[] buf = new byte[num];
is.read(buf);
System.out.println(new String(buf));


is.close();
}
}

13、复制图片到指定位置。


import java.io.*;
class CopyPic
{
public static void main(String[] args)
{
copyPic("temp.jpg","D:\\temp.jpg");
}
public static void copyPic(String res,String des)
{
FileInputStream is = null;
FileOutputStream os = null;
int num = 0;
byte[] buf = new byte[1024];
try
{
is = new FileInputStream(res);
os = new FileOutputStream(des);
while((num=is.read(buf))!=-1)
{
os.write(buf,0,num);
}
}
catch (IOException e)
{
throw new RuntimeException("创建流失败");
}
finally
{
if(is!=null)
{
try
{
is.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
finally
{
if(os!=null)
{
try
{
os.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
}
}
}
}
}
}

14、字节流缓冲区BufferedInputStream  BufferedOutputStream
拷贝MP3,通过缓冲区。


import java.io.*;
class CopyMp3
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
copyMp3("E:\\Music\\Adele - Someone Like You.mp3","D:\\someone.mp3");
long end = System.currentTimeMillis();
System.out.println(end-start);
}
public static void copyMp3(String res,String des)
{
BufferedInputStream bis =null;
BufferedOutputStream bos = null;
byte[] buf = new byte[1024];
int num = 0;
try
{
bis = new BufferedInputStream(new FileInputStream(res));
bos = new BufferedOutputStream(new FileOutputStream(des));
while((num=bis.read(buf))!=-1)
{
bos.write(buf,0,num);
}
}
catch (IOException e)
{
throw new RuntimeException("创建流失败");
}
finally
{
if(bis!=null)
{
try
{
bis.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
finally
{
if(bos!=null)
{
try
{
bos.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
}
}
}
}
}
}

15自定义字节流缓冲区

import java.io.*;
class MyBufferedInputStream
{
private InputStream is;
private byte[] buf = new byte[1024];
private int pos = 0, count = 0;
MyBufferedInputStream(InputStream is)
{
this.is = is;
}
public int myRead()throws IOException
{
//通过is对象读取字节,并存入buf中。
if(count==0)
{
count = is.read(buf);
if(count<0)
return -1;
pos=0;
byte b = buf[pos];
count--;
pos++;
return b&255;
}
else if(count>0)
{
byte b = buf[pos];
count--;
pos++;
return b&255;
}
return -1;
}
public void myClose()throws IOException
{
is.close();
}
}


流文件可能出现以下数据形式
11111111-11100000-00000000-01010101-01010010-10101010-10110101-0....


一个字节为8位二进制代码
当读取一个字节为11111111时,此时该字节标示-1;
00000001去反
11111110+1
11111111=-1;
与结束标志相同。
为了避免上述情况发生
将byte转换成int 
byte -1 --->int -1
 11111111-11111111-11111111-11111111
&00000000-00000000-00000000-11111111
---------------------------------------
 00000000-00000000-00000000-11111111=255 返回元数据,并避免了返回-1的情况。


16、读取转换流和写入转换流。

import java.io.*;
class TransStreamDemo
{
public static void main(String[] args)throws IOException
{
OutputStreamWriterDemo();
}
public static void InputStreamReaderDemo()throws IOException
{
BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream("www.txt")));
String s = null;
while(true)//这么写有问题。读取文件时,会抛出空指针异常。
{
s = bf.readLine();
if(s.equals("over"))
break;
System.out.println(s);
}
}
public static void OutputStreamWriterDemo()throws IOException
{

BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream("www.txt")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String s = null;
while((s=bf.readLine())!=null)//如果写while(true)的话在读取文件到最后时会导致s = null,后面输出无法进行,抛出空指针异常。
{
if(s.equals("over"))
break;
bw.write(s);
bw.newLine();
bw.flush();
}
bf.close();
bw.close();
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值