Java作业九

(一)学习总结

1.用思维导图对javaIO操作的学习内容进行总结。
1082644-20170525122724107-1119146062.png

2.下面的程序实现了文件的拷贝,但采用的是一个字节一个字节的读写方式,效率很低。使用缓冲区可以减少对文件的操作次数,从而提高读写数据的效率。IO包中提供了两个带缓冲的字节流BufferedInputStream和BufferedOutputStream,查阅JDK帮助文档,修改程序,利用这两个类完成文件拷贝,对比执行效率。

import java.io.*;
public class Test{
    public static void main(String args[]) {
        FileInputStream in=null;
        FileOutputStream out=null;
        File fSource=new File("d:"+File.separator+"my.jpg");
        File fDest=new File("d:"+File.separator+"java"+File.separator+"my.jpg");
        if(!fSource.exists()){ 
            System.out.println("源文件不存在");   
            System.exit(1);   
        }
        if(!fDest.getParentFile().exists()){   
            fDest.getParentFile().mkdirs();     
        }
        try {   
            in=new FileInputStream(fSource);
            out=new FileOutputStream(fDest);
            int len=0;
            long begintime = System.currentTimeMillis();
            while((len=in.read())!=-1){
                out.write(len);          
            } 
            long endtime = System.currentTimeMillis();
            System.out.println("文件拷贝完成,耗时"
                            +(endtime-begintime)+"毫秒");
        }catch(Exception e){
            System.out.println("文件操作失败");  
        }finally{       
            try {   
                in.close();   
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }      
        }     
    }
}

BufferedInputStream是带缓冲区的输入流,默认缓冲区大小是8M,能够减少访问磁盘的次数,提高文件读取性能;BufferedOutputStream是带缓冲区的输出流,能够提高文件的写入效率。BufferedInputStream与BufferedOutputStream分别是FilterInputStream类和FilterOutputStream类的子类,实现了装饰设计模式。

其他:
BufferedInputStream类的例子

import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BufferedInputStreamDemo01{

    // 声明常量
        public static final int SIZE=1024;

    public static void main(String[] args){
       //变量声明
           File f=null;
       InputStream input=null;
       BufferedInputStream bis=null;
           StringBuilder strBuild=null;
       SimpleDateFormat sdf=null;
       Date d=null;
           long start=0L;
       long end=0L; 

          try{
          sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
          
          strBuild=new StringBuilder();
                  start=System.currentTimeMillis();
          d=new Date();
          if(d!=null){
                  d.setTime(start);
         }
          System.out.println("程序开始执行时间:"+sdf.format(d));

      f=new File("d:"+File.separator+"demo.txt");
          input=new FileInputStream(f);
          // 指定文件带缓冲区的读取流且指定缓冲区大小为2KB
      bis=new BufferedInputStream(input,2*SIZE);
          int bisLength=bis.available();
          int readLength=0;
          byte[] byteArray=new byte[SIZE];
          int tmp=0;
          while((tmp=bis.read(byteArray))!=-1){ 
                strBuild.append(new String(byteArray,0,tmp));
        System.out.println("每次读取字节数量:"+tmp);
        System.out.println("文件中剩余字节数:"+input.available());
     }
          
          System.out.println(String.format("文件的大小:%d,缓冲区读取流返回的大小:%d",f.length(),bisLength));
      System.out.println("文件的内容:"+strBuild.toString());
      System.out.println("字符串长度:"+strBuild.toString().length());
      char[] cTmp=strBuild.toString().toCharArray();
      System.out.println("字符串->字符数组长度:"+cTmp.length);

      end=System.currentTimeMillis();
      d=new Date();
      if(d!=null){ 
         d.setTime(end);
      }
      System.out.println("程序执行的结束时间:"+sdf.format(d));
      System.out.println("<-------------******************---------------->");
      System.out.println("程序执行时间(ms):"+(end-start)+"毫秒");

       }catch(FileNotFoundException ex){
          ex.printStackTrace();
       }catch(IOException ex){
          ex.printStackTrace();
       }finally{
         try{
               if(input!=null){
         input.close();
        }
           if(bis!=null){
         bis.close(); 
           }
         }catch(IOException ex){
           ex.printStackTrace();
         }
      }
   }
}

BufferedOutputStream类的例子:

import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BufferedOutputStreamDemo01{
        public static final int SIZE=1024;
        public static final String DRIVERNAME="oracle.jdbc.driver.OracleDriver";
        public static final String DBURL="jdbc:oracle:thin:@IP:1521:DB名称";
    public static final String USERNAME="用户名";
    public static final String PASSWORD="密码";
    
    static{
       try{
            // 加载驱动程序
            Class.forName(DRIVERNAME);
          }catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }
    }

    public static void main(String[] args){
       // 变量声明
       File f=null;
       OutputStream output=null; 
       BufferedOutputStream bos=null;
           Connection con=null;
       PreparedStatement pst=null;
           ResultSet rs=null;
       StringBuilder strBuild=null;
 
           try{
          String sql=" select vendor_no,vendor_name,address,phone,email,zipcode from VENDOR";
           
          con=new BufferedOutputStreamDemo01().getConnection();
                  // 获得数据库操作类
                  pst=new BufferedOutputStreamDemo01().getPst(con,sql);
                  // 获得结果集
          rs=pst.executeQuery();

          f=new File("F:"+File.separator+"tmp.txt");
          output=new FileOutputStream(f,false);
          bos=new BufferedOutputStream(output,SIZE*4);
          
          while(rs.next()){
                        strBuild=new StringBuilder();
            
            // 店号
            strBuild.append(rs.getString("vendor_no"));
            strBuild.append(",");

                        // 店名
            strBuild.append(rs.getString("vendor_name"));
            strBuild.append(",");
            
            // 地址
            strBuild.append(rs.getString("address"));
            strBuild.append(",");
            
            // 电话
            strBuild.append(rs.getString("phone"));
            strBuild.append(",");

                        // 邮件
            strBuild.append(rs.getString("email"));
            strBuild.append(",");

                        // 邮政编码
            strBuild.append(rs.getString("zipcode"));
            strBuild.append("\n");
            
                        bos.write(strBuild.toString().getBytes("utf-8"));
          }

           }catch(IOException ex1){
               ex1.printStackTrace();
       }catch(SQLException ex){
           ex.printStackTrace();
       }finally{
               try{
             // 关闭流
             if(output!=null){
               output.close(); 
             }
             if(bos!=null){
                            bos.close();
             } 
             //关闭数据库连接
             if(rs!=null){
                            rs.close();
             }
                         if(pst!=null){
                            pst.close();
             }
                         if(con!=null){
               con.close();
             }
                 }catch(IOException ex){
                ex.printStackTrace();
                 }catch(SQLException ex){
                    ex.printStackTrace();
             }
         }
    }
    
    /**
        **获得数据库连接
    **
    **/
    public static Connection getConnection(){
       Connection con=null;
       try{
           // 获得数据库连接
           con=DriverManager.getConnection(DBURL,USERNAME,PASSWORD);
       }catch(SQLException ex){
           ex.printStackTrace();
       } 

       return con;
    }
    
    /**
        **获得数据库操作类
    **/
    public static PreparedStatement getPst(Connection con,String sql){
            PreparedStatement pst=null;
        try{
          pst=con.prepareStatement(sql);
           }catch(SQLException ex){
          ex.printStackTrace();
           } 

        return pst;
    }
}

public String[] list()方法可以列出指定目录的全部内容,但是只是列出了名称。而public File[] listFiles()除了会列出指定目录的全部内容还会列出路径。创建新的文件夹必
须给出完整的路径

File f = new File("具体路径");
try{
    f.createNewFile();
}
catch(IOException e){
    e.printStackTrace();
}

删除文件

public static void mian(String args[]){
    File f = new File("d:"+File.separator+"test.txt");    //必须给出路径
    f.delete();                   //if(f.zxists()){ f.delete();}        在删除中增加判断
}

创建可以直接使用mkdir()方法完成。

(二)实验总结

实验内容:
1.宠物商店:在实验八的基础上,增加一个功能,用文件保存每日的交易信息记录。
2.完成文件复制操作,在程序运行后,提示输入源文件路径和目标文件路径。

(三)代码托管 https://git.oschina.net/ying971227/Java-CS01zzy.git

1082644-20170525183345779-352145160.png

转载于:https://www.cnblogs.com/zhaoziying/p/6903704.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值