JAVA IO操作(二)流

一、字节流与字符流


   操作步骤:
       *1.首先通过File类对象找到操作文件路径(没有要创建)
       *2.通过字节流或字符流的子类为字节流或字符流的对象实例化(向上转型)
       *3.执行读写操作
       *4.关闭操作的资源close();
   1.字节流
       1-字节输出流:OutputStream:
       实例化:OutputStream output=new FileOutputStream(file)throws Exception
       实例化(不替换)OutputStream output=new FileOutputStream(file,true)
       进行输出:*单字节输出:public abstract void write(int b);
                           *一组字节数组:public void write(byte [] b);
                           *输出部分字节数组:public void write(byte[] b,int off,int len);
       2-字节输入流:InputStream:
       进行读取:*读取单个字节:public abstract int read()throws IOException;
                           *对区多个字节:public int read(byte[] b);

                           *读取指定多个字节:public int read(byte[] b,int off,int len); 

 

File file =new File("D:/hello.txt");
 //字节流
 //字节输入流
InputStream input=new FileInputStream(file);
byte[] bs=new byte[1024];
int len=input.read(bs);//字节长度
System.out.println(new String(bs,0,len)); 
input.close();
字节输出流
OutputStream output=new FileOutputStream(file,true);
String str="十步杀一人,千里不留行。";
output.write(str.getBytes());
input.close();

  

2.字符流:
      1-字符输出流:Writer
       输出一个字符串(重):public void write(String str)throws IOException;
      2-字符输入流:Reader:
       读取字符数组:public int read(char[] ch);

 

//字符流:
    //字符输入流
	Reader re=new FileReader(file);
	char [] ch=new char[1024];
	int len=re.read(ch);
	System.out.println(new String(ch,0,len));
	re.close();
   //字符输出流:
	Writer wr=new FileWriter(file);
	String a="飞流直下三千尺,疑是银河落九天。";
	wr.write(a);
	wr.flush();
	wr.close();

  3.文件的复制:

 

public class Test3 {
	public static void main(String[] args) throws IOException {
		//复制文件:
		InputStream input=new FileInputStream(new File("D:/x.jpg"));
		OutputStream output=new FileOutputStream(new File("D:/workspace/as.jpg"));
		byte[] bs=new byte[1024];
		int len;
		while((len=input.read(bs))!=-1) {
			output.write(bs,0,len);
		}
		input.close();
		output.close();
	}
}

 

字节流与字符流对比:

           字节流在进行IO操作的时候,直接针对的是操作的数据终端(文件),而字符流操作的时候不是直接针对于终端,而是针对于缓冲区(理解为内存)操作,而后有缓存取操作终端,属间接操作。

           注:在使用字节流时不关闭最后的输出流操作,也可以将内容进行输出,而字符输出流的时候如果不关闭,则内容不会输出,需要由用户自己调用flush()方法强制手工清空。

           注:使用最多的数据类型都是字节数据,包括图片,音乐,各种可执行程序都是字节数据,所以字节流比字符流用的多,但进行中文处理的时候,考虑使用字符流。

 

二、转换流


   *将字节输出流变为字符输出流:OutputStreamWriter

   *将字节输入流变为字符输入流:InputStreamReader

 

//转换流:
		//1.将字节输出流转换为字符输出流
		OutputStream output=new FileOutputStream(file);
		Writer out=new OutputStreamWriter(output);
		out.write("天涯明月刀");
		out.close();
		//2.将字节输入流转换为字符输入流
		InputStream input=new FileInputStream(file);
		Reader in=new InputStreamReader(input);
		char [] ch=new char[1024];
		int len=in.read(ch);
		System.out.println(new String(ch,0,len));

三、内存操作流

       字节内存操作流:内存输入流(ByteArrayInputStream),内存输出流(ByteArrayOutputStream);

       字符内存操作流:内存输入流(CharArrayReader),内存输出流(CharArraWriter)

public class Testdemo{
   public static void main (String[] args) throws Exception{
          String str="hello world.";
          InputStream input= new ByteArrayInputStream(str,getBytes());//将数据输出到内存之中
          OutputStream output= new ByteArrayOutputStream();//准备从内存之中读取数据
           int temp=0;
          while((temp=input.read())!=-1){
            output.write((char)Character.toUpperCase(temp));//所有内容都在字节输出流中
          }
         String newStr = output.toString();//取数据
         output.close();
         input.close();
         System.out.println(newStr);
   }
}

 

四、打印流

PrintStream(字节打印流)PrintWriter(字符打印流)

主要以字节打印流为主,字符打印流主要用于方便的输入中文。

-PrintStream out = new PrintStream(new FileOutputStream(new File(文件地址);

-格式化输出:public PrintStream printf(String format,Object

PrintStream p=new PrintStream(new FileOutputStream(file));
		p.print("莫道黯然销魂,");
		p.print("何处柳暗花明。");

System类:

       System类的一些定义:

         -错误输出:public static final PrintStream err;

         -系统输出:public static final PrintStream out;

         -系统输入:public static final PrintStream in;

     系统输出:将所有的信息输入到指定的输出设备上(显示器),System.in属于PrintStream对象,PrintStream是OutputStream子类,so可以利用System.out为OutputStream类执行实例化操作:

例;OutputStream output=System.out;
   output.write("hello World.".getBytes());
例:InputStream input = System.in;
    byte data[] = new byte[1024];
    System.out.print("请输入数据;");
    int len=input.read(data);

 


五、缓冲输入输出流

缓冲流,是在别的流上加上缓冲提高效率,当对文件或其他目标频繁读写或操作效率低,效能差。这时使用缓冲流能够更高效的读写信息。因为缓冲流先将数据缓存起来,然后一起写入或读取出来。

分为字节和字符缓冲流:

BufferInputStream 字节缓冲输入流 作用是为其它输入流提供缓冲功能

BufferOutputStream 缓冲输出流

public static void write() throws IOException {
    OutputStream out =new FileOutputStream("F:\\test.txt");
    BufferedOutputStream buf = new BufferedOutputStream(out);//缓冲流
    String data  = "天之道,损有余而补不足。";
    buf.write(data.getBytes());
    buf.flush(); //刷新缓冲区,内容写入
    buf.close();
    out.close();
}
public static void read() throws IOException {
    InputStream in =new FileInputStream("F:\\test.txt");
    BufferedInputStream buf = new BufferedInputStream(in);
    byte[] bytes=new byte[1024];
    int len=-1;
    while ((len=buf.read(bytes))!=-1){
        System.out.println( new String(bytes,0,len));
    }
}

 

字符缓冲流:

BufferReader -字符输入缓冲流   BufferWriter 字符输出缓冲流

使用BufferedReader的原因在于BufferedReader类有一个方法可以读取一行数据。

BufferedReader类构造方法:public BufferedReader(Reader in)

BufferedReader类之中的readLine()返回的是String数据,而String数据更加方便

File file=new File("D:/hello.txt");
		FileWriter writer=new FileWriter(file);
		BufferedWriter buff=new BufferedWriter(writer);
		buff.write("zhangsan");
		buff.newLine();
		buff.write("lisi");
		buff.close();
		FileReader reader =new FileReader(file);
		BufferedReader buffreader =new BufferedReader(reader);
		String str;
		while((str=buffreader.readLine())!=null) {
			System.out.println(str);
		}
		buffreader.close();
		reader.close();
	}
}

 

六、Scanner类

 java.util.Scanner类,是工具类,Scanner中定义的主要操作方法:

      -构造方法:public Scanner(InputStream source);

     -判断是否有数据:public Boolean hasNextXxx();

     -取得数据:public 数据类型 nextXxx();

     -修改分隔符:public Scanner useDelimiter(String pattern);

     调用执行nextXxx()之前首先使用hasNextXxx()判断是否有指定格式的数据出现:

例:Scanner scan = new Scanner(System.in);
  	    scan.useDelimiter("\n");
    System.out.print("请输入数据:");
    if(scan.hasNext()){
          String str=scan.next();
          System.out.println("输入数据:"+str);
    } 
例:使用Scanner判断输入数据是否为数字:
       Scanner scan= new Scanner(System.in);
       System.out.println("请输入数据:");
       if(scan.hasNextDouble()){
              double data = scan.nextDouble();
              System.out.println("输入数据:"+data);
       }else{
              System.out.println("输入的不是数字");
例:使用Scanner读取文件:
        Scanner scan = new Scanner(new FileInputStream(new File(文件位置)));
        scan.useDelimiter("\n");
        while(scan.hasNext()){
                System.out.println(scan.next());
             }
        scan.close();

七、压缩流

压缩流:使用输入输出压缩解压zip,rar文件

ZipInputStream :压缩文件输入流:读取磁盘上的压缩文件;

ZipOutStream:用于将程序中的压缩流写出到磁盘上;

 

//单文件压缩
private static void yasuoFile(){
    System.out.println("开始压缩");
    String zipFileName = "E:\\tests.zip";
    File file = new File("E:\\123.txt");
    try {
        ZipOutputStream out  = new ZipOutputStream(new FileOutputStream(zipFileName));//生成压缩文件
        out.putNextEntry(new ZipEntry(file.getName())); //往里加文件
        //读取原文件内容,写入到压缩文件里
        InputStream inputStream=new FileInputStream(file);
        BufferedInputStream bis=new BufferedInputStream(inputStream); //缓冲输入 (获取文件内容)
        BufferedOutputStream bos = new BufferedOutputStream(out);    //缓冲输出 (输出到zip流里)
        byte[] bytes=new byte[1024];
        int len=-1;
        while ((len=bis.read(bytes))!=-1){
            bos.write(bytes,0,len);
        }
        bos.close();
        bis.close();
        out.close();
        System.out.println("压缩完成");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
//第一个参数是压缩的名字,第二个参数是要压缩的目录
yasuoFolder("F:\\test.zip",new File("F:\\test"));
//压缩文件夹:
private static void yasuoFolder(String zipFileName, File file){
    System.out.println("开始压缩");
    try {
        ZipOutputStream out  = new ZipOutputStream(new FileOutputStream(zipFileName));
        BufferedOutputStream bos = new BufferedOutputStream(out);
        zipFolder(out,file,file.getName(),bos);
        bos.close();
        out.close();
        System.out.println("压缩完成");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private static void zipFolder(ZipOutputStream zout, File target, String name, BufferedOutputStream bos)  {
    //判断是不是目录
    try {
    if (target.isDirectory()){
        File[] files=target.listFiles();
        if (files.length==0){//空目录
                zout.putNextEntry(new ZipEntry(name+"/"));
        }
        for (File f:files){
            zipFolder(zout,f,name+"/"+f.getName(),bos); //递归处理
        }
    }else {
        zout.putNextEntry(new ZipEntry(name));
        InputStream inputStream=new FileInputStream(target);
        BufferedInputStream bis=new BufferedInputStream(inputStream);
        byte[] bytes=new byte[1024];
        int len=-1;
        while ((len=bis.read(bytes))!=-1){
            bos.write(bytes,0,len);
        }
        bis.close();
    }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

 

 

 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值