zoukankan      html  css  js  c++  java
  • java基础--IO流

    /**
     * 以程序为中心
     * IO流分类
     *
     * 1.流向:输入流和输出流
     * 2.数据:字节流:二进制,包括一切文件 文本,音频,视频等
     *       字符流:文本文件,只能处理纯文本
     * 4.功能:节点:包裹源头
     *       处理增强功能:提供性能
     * 字节与字符流
     *
     * 字节流
     * 输入流 InputStream
     *
     *      FileInputStream
     * 输出流  OutputStream
     *      FileOutputStream
     * 字符流
     * Reader 输入流
     *      FileReader
     *
     * Writer 输出流
     *      FileWriter

        为了达到最高效率,可要考虑在 BufferedReader 内包装 InputStreamReader。例如:

     BufferedReader in
       = new BufferedReader(new InputStreamReader(System.in));
    


     *
     * @author Administrator
     *
     * 缓冲流   提高性能
     *     字节缓冲流
     *           BufferedInputStream
     *     字符缓冲流
     *           BufferedReadStream
     * 字节数组流  ByteArrayOutputStream    ByteArrayInputStream

     * 数据流   DataInputStream DataOutputStream  
     * 对象流  序列化,反序列化
     * 打印流 PrintStream
     */

    public class Io {
        
        
        //拷贝文件
        public static void copyFile(File src,File to) throws Exception{
            InputStream is = new BufferedInputStream(new FileInputStream(src));
            OutputStream ou = new FileOutputStream(to);
            byte []b = new byte[1024];
            int len = 0;
            while(-1!=(len=is.read(b))){
                ou.write(b, 0, len);
            }
            ou.flush();
            ou.close();
            is.close();
        }
        
        //字符流
        public static void charIo() throws Exception{
            File file = new File("F:/test/a.txt");
            Reader reader = new FileReader(file);
            char [] ch = new char[1024];
            int len =0;
            int i = 0;
            while(-1!=(len=reader.read(ch))){
                String str = new String(ch,0,len);
                System.out.println(str);
                i++;
            }
            
            System.out.println(i);
        }
        
        
        
        //拷贝文件夹/文件夹不可以覆盖,文件可以覆盖
        public static void copyDir() throws Exception{
            String srcPath = "F:/test/from";
            String toPath = "F:/test/to";
            File srcFile = new File(srcPath);
            File toFile = new File(toPath);
            if(srcFile.isDirectory()){
                toFile = new File(toPath,srcFile.getName());
            }
            copyDirDetail(srcFile, toFile);
            
        }
        
        public static void copyDirDetail(File src,File to) throws Exception{
            if(src.isFile()){
                copyFile(src, to);
            }else if(src.isDirectory()){
                to.mkdirs();
                for(File sub:src.listFiles()){
                    copyDirDetail(sub,new File(to,sub.getName()));
                }
            }
        }
        
        
        public static void print() throws FileNotFoundException{
            PrintStream printStream = new PrintStream(new File("F:/test/aa/txt"));
            printStream.print("asdfasdfasdf");
            
            
        }

    //递归文件夹的所有文件
        public static void printName(File src){
            if(src==null||src.exists()){
                return;
            }
            System.out.println(src.getAbsolutePath());
            if(src.isDirectory()){
                for (File file : src.listFiles()) {
                    printName(file);
                }
            }
        }
    public static void main(String[] args) throws Exception { //流读取不了文件夹 /*File src = new File("E:/a.txt"); InputStream is = new FileInputStream(src); byte []buff = new byte[1024]; int len = 0;//实际接收大小 while((len=is.read(buff))!=-1){ String content = new String(buff, 0, len); } OutputStream ou = new FileOutputStream(src); String s = "1212"; ou.write(s.getBytes()); ou.flush(); ou.close();*/ //copyDir(); //copyFile(new File("F:/test/1.txt"), new File("F:/test/a/2.txt")); //charIo(); print(); } }

    //src.mkdir();//必须有父目录

    //src.mkdirs();//如果没有父目录  则创建

    File [] roots = File.listRoots();//所有盘符

    System.out.println(Arrays.toString(roots));

    /**
         * 转file
         * @param multipartFile
         * @return
         */
        private File toFile(MultipartFile multipartFile){
            InputStream ins = null;
            File f = null;
            try {
                ins = multipartFile.getInputStream();
                f=new File(multipartFile.getOriginalFilename());
                FileUtils.copyInputStreamToFile(ins, f);
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(ins!=null){
                    try {
                        ins.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return f;
        }
    @RequestMapping("/gwcs/download.do")
        public void downloadFile(HttpServletRequest request,
                HttpServletResponse response,String id) throws Exception {
            InputStream is = null;
            OutputStream os = null;
            File file = null;
            try {
                
                Map map = new HashMap();
                map.put("id", id);
                Map resultMap=dowloadSrvImp.execute(map);
                DoctranFujian fujian=(DoctranFujian)resultMap.get("fujian");
                String fileName = fujian.getFilename();
                
                file = FTPUtils.getInstance().retrieve(
                        fujian.getCebid(), fujian.getId());
                /*
                 * @modify by xhb 此处增加按文件名设置response返回头信息主要应用于公文套头时按原文格式生成新正文
                 */
                
                String userAgent = request.getHeader("User-agent");
                
                //针对IE或者以IE为内核的浏览器:
                if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                } else {
                //非IE浏览器的处理:
                    fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
                }
                //byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");
                //fileName = new String(bytes, "ISO-8859-1"); 
                response.setHeader("Content-disposition", String.format("attachment; filename="%s"", fileName));
                
                /*if (StringUtils.isNotBlank(fileName)) {
                    response.setHeader("Content-Disposition",
                            "attachment;fileName=" + fileName);
                }*/
                //以下代码所执行的业务在BaseAction中的responseOutputFile()方法都实现了
                //因为在service.downloadFile()方法中,还写有下载业务,主要是下载的文件名
                //所以没法调用BaseAction中的方法,只能重新一遍
                //优化:孙敬哲,2016-4-29 解决下载大文件有可能造成内存溢出
                is = new FileInputStream(file);
                if (is != null) {
                    // 获取响应的输入流
                    os = response.getOutputStream();
                    // 使用此方法,可以减少内存使用,不会因为打附件造成内存溢出
                    byte[] data = new byte[1024 * 4];
                    int l = 0;
                    while ((l = is.read(data)) > 0) {
                        // 强制刷新字节流中的未写出数据,当用户点击取消下载时,强制刷新后不会报连接失败的异常
                        os.flush();
                        // 不直接使用os.write(data),会为原文件写入过多无用字节,造成文件变大
                        os.write(data, 0, l);
                    }
                }
            } catch (Exception e) {
                // 如果为SocketException异常,则不处理,否则其他异常则抛出
                if (!(e.getCause() instanceof SocketException)) {
                    throw e;
                }
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (Exception e) {
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                    }
                }
                // 从ftp下载的文件,供用户下载,如果用户已下载,则删除临时文件
                if (file != null && file.exists()) {
                    try {
                        file.delete();
                    } catch (Exception e) {
                    }
                }
            }
        }
  • 相关阅读:
    vue.js环境配置步骤及npm run dev报错解决方案
    消息处理之performSelector
    iOS开发网络篇—发送GET和POST请求(使用NSURLSession)
    iOS手机号正则表达式并实现344格式 (正则的另一种实现方式)
    IOS开发——正则表达式验证手机号、密码
    iOS网络请求之---GET和POST
    CLLocation
    ios本地文件内容读取,.json .plist 文件读写
    UITableViewCell的4种样式
    iOS开发通过代码方式使用AutoLayout (NSLayoutConstraint + Masonry)
  • 原文地址:https://www.cnblogs.com/jentary/p/6080740.html
Copyright © 2011-2022 走看看