java中的可释放资源定义,类似c#中的using

时间:2022-08-30 08:03:38
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");
    }