zoukankan      html  css  js  c++  java
  • java中的可释放资源定义,类似c#中的using

    public static class FileDuplicator implements AutoCloseable
        {
            Scanner in = null;
            PrintWriter out = null;
            
            public FileDuplicator(String sourceFile, String destFile) {
                try {
                    in = new Scanner(new FileInputStream(sourceFile));
                    out = new PrintWriter(destFile);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
    
            public void copy()
            {
                while(in.hasNext())
                {
                    out.println(in.next().toUpperCase());
                }
                out.flush();
                in.close();
                in = null;
                out.close();
                out = null;
            }
            
            @Override
            public void close() throws Exception {
                if(in != null)
                    in.close();
                if(out != null)
                    out.close();
            }
        }
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.text.DecimalFormat;
    import java.util.ArrayList;
    import java.util.EventListener;
    import java.util.List;
    import java.util.Scanner;
    
    public class Test {
        
        public static void main(String[] args) throws FileNotFoundException 
        {
            try (FileDuplicator fd = new FileDuplicator("f:\test.txt", "f:\test2.txt"))
            {
                fd.copy();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            try(Scanner in = new Scanner(new FileInputStream("f:\test.txt"));)
            {
                
            }
            
            System.out.println("end");
        }
  • 相关阅读:
    jdk7_ConcurrentHashMap 图示
    Teradata 日期函数
    Teradata正则表达式
    Teradata sql去除字段中的字母/数字
    sql查询连续3天有交易记录的客户
    批量生成sql查询语句
    sql查询字段中是否含有字母/数字/符号
    sql查询每个人最新的2个电话号码
    python连接Teradata数据库
    dos命令获取文件行数
  • 原文地址:https://www.cnblogs.com/nanfei/p/8430918.html
Copyright © 2011-2022 走看看