자바 프로 그래 밍 (고급 및 테마) - IO 흐름 과 직렬 화

77907 단어 Java
  • 오늘 우 리 는 I / O 흐름 과 직렬 화 문 제 를 이야기 합 니까?개인 적 인 이해: 우리 가 프로 그래 밍 개발 을 할 때 파일 의 읽 기와 쓰기 와 관련 되 는데 자바 가 우리 에 게 제공 하 는 I / O 흐름 은 바로 이 문 제 를 해결 하 는 데 쓰 인 다.우 리 는 파일 을 읽 고 기록 할 때 직렬 화 된 것 과 관련 이 있 습 니 다. 직렬 화 에 대해 서 는 인 코딩 형식 을 떠 날 수 없습니다. 우리 의 windows 는 GBK 로 인 코딩 되 고 우리 의 자바 는 보통 UTF - 8 로 인 코딩 됩 니 다. 그래서 우 리 는 가끔 어 지 러 운 문 제 를 개발 할 때 당황 하지 마 세 요. 문 제 는 항상 해결 할 수 있 습 니 다. 새로 오 는 것 이 아 닙 니까?입력 스 트림 바이트 입력 스 트림 (파일 기록), 출력 스 트림 바이트 출력 스 트림 (파일 읽 기), Reader 문자 입력 스 트림 (파일 기록), Writer 문자 출력 스 트림 (파일 읽 기), File 파일 클래스 (파일 경로), Serializable 표지 인터페이스 (직렬 화 된 표준) 등 다섯 가지 인터페이스 키 가 있 습 니 다.그리고 transient (반 직렬 화 키워드);하나의 문 자 는 두 개의 바이트 와 같 습 니 다. 문자 흐름 이 처리 할 수 있 는 바이트 흐름 은 모두 처리 할 수 있 습 니 다. 문자 흐름 이 반드시 바이트 흐름 을 처리 할 수 있 는 것 은 아 닙 니 다.

  • 파일 클래스
    /*
    File         (     )
    	File.separator        //
    	      ,       :e:\\work\\workspace\\ioDemo\\txt\\aaa.txt
    	        ,      .classpath  
    	f1.createNewFile();        ,       
    	file.list();//                   String  
    */
           File f=new File("D:"+File.separator+"aaa"+File.separator+"aaa.txt");
    		/*
    		File f1=new File("D:"+File.separator+"aaa","aaa.txt");
    		
    		File parent=new File("D:"+File.separator+"aaa");
    		File child=new File(parent,"aaa.txt");*/
    

    다음은 그것 의 몇 가지 방법 이다.
    번호
    방법.
    소개 하 다.
    1
    public String getName()
    추상 적 인 경로 이름 으로 표 시 된 파일 이나 디 렉 터 리 의 이름 을 되 돌려 줍 니 다.
    2
    public String getParent()
    이 추상 적 인 경로 이름 의 부모 경로 이름 의 경로 이름 문자열 을 되 돌려 줍 니 다. 이 경로 이름 이 부모 디 렉 터 리 를 지정 하지 않 으 면 null 로 돌아 갑 니 다.
    3
    public File getParentFile()
    이 추상 적 인 경로 이름 의 부모 경로 이름 의 추상 적 인 경로 이름 을 되 돌려 줍 니 다. 이 경로 이름 이 부모 디 렉 터 리 를 지정 하지 않 으 면 null 로 돌아 갑 니 다.
    4
    public String getPath()
    이 추상 적 인 경로 이름 을 경로 이름 문자열 로 변환 합 니 다.
    5
    public boolean isAbsolute()
    이 추상 적 인 경로 이름 이 절대 경로 이름 인지 테스트 합 니 다.
    6
    public String getAbsolutePath()
    추상 적 인 경로 이름 의 절대 경로 이름 문자열 을 되 돌려 줍 니 다.
    7
    public boolean canRead()
    프로그램 이 이 추상 적 인 경로 이름 으로 표 시 된 파일 을 읽 을 수 있 는 지 시험 합 니 다.
    8
    public boolean canWrite()
    프로그램 이 이 추상 적 인 경로 이름 으로 표 시 된 파일 을 수정 할 수 있 는 지 시험 합 니 다.
    9
    public boolean exists()
    이 추상 적 인 경로 이름 이 표시 하 는 파일 이나 디 렉 터 리 가 존재 하 는 지 테스트 합 니 다.
    10
    public boolean isDirectory()
    이 추상 적 인 경로 이름 이 표시 하 는 파일 이 디 렉 터 리 인지 테스트 합 니 다.
    11
    public boolean isFile()
    이 추상 적 인 경로 이름 이 표시 하 는 파일 이 표준 파일 인지 테스트 합 니 다.
    12
    public long lastModified()
    이 추상 적 인 경로 이름 으로 표 시 된 파일 이 마지막 으로 수 정 된 시간 을 되 돌려 줍 니 다.
    13
    public long length()
    추상 적 인 경로 이름 으로 표 시 된 파일 의 길 이 를 되 돌려 줍 니 다.
    14
    public boolean createNewFile() throws IOException
    이 추상 적 인 경로 이름 이 지정 한 이름 을 가 진 파일 이 존재 하지 않 을 때 이 추상 적 인 경로 이름 으로 지정 한 새로운 빈 파일 을 원자 적 으로 만 듭 니 다.
    15
    public boolean delete()
    이 추상 적 인 경로 이름 이 표시 하 는 파일 이나 디 렉 터 리 를 삭제 합 니 다.
    16
    public void deleteOnExit()
    가상 컴퓨터 가 종 료 될 때 이 추상 적 인 경로 이름 이 표시 하 는 파일 이나 디 렉 터 리 를 삭제 해 달라 고 요청 합 니 다.
    17
    public String[] list()
    이 추상 적 인 경로 이름 으로 표 시 된 디 렉 터 리 의 파일 과 디 렉 터 리 의 이름 으로 구 성 된 문자열 배열 을 되 돌려 줍 니 다.
    18
    public String[] list(FilenameFilter filter)
    디 렉 터 리 에 포 함 된 파일 과 디 렉 터 리 의 이름 으로 구 성 된 문자열 배열 을 되 돌려 줍 니 다. 이 디 렉 터 리 는 지정 한 필 터 를 만족 시 키 는 추상 적 인 경로 이름 을 통 해 표 시 됩 니 다.
    19
    public File[] listFiles()
    추상 적 인 경로 이름 배열 을 되 돌려 줍 니 다. 이 경로 이름 들 은 이 추상 적 인 경로 이름 이 디 렉 터 리 에 있 는 파일 을 표시 합 니 다.
    20
    public File[] listFiles(FileFilter filter)
    이 추상 적 인 경로 이름 이 디 렉 터 리 에 있 는 파일 과 디 렉 터 리 를 나타 내 는 추상 적 인 경로 이름 배열 을 되 돌려 줍 니 다. 이 경로 이름 들 은 특정한 필 터 를 만족 시 킵 니 다.
    21
    public boolean mkdir()
    이 추상 적 인 경로 이름 이 지정 한 디 렉 터 리 를 만 듭 니 다.
    22
    public boolean mkdirs()
    이 추상 적 인 경로 이름 이 지정 한 디 렉 터 리 를 만 듭 니 다. 필요 하지만 존재 하지 않 는 부모 디 렉 터 리 를 만 드 는 것 을 포함 합 니 다.
    23
    public boolean renameTo(File dest)
    이 추상 적 인 경로 이름 이 표시 하 는 파일 의 이름 을 바 꿉 니 다.
    24
    public boolean setLastModified(long time)
    이 추상 적 인 경로 이름 으로 지정 한 파일 이나 디 렉 터 리 의 마지막 수정 시간 을 설정 합 니 다.
    25
    public boolean setReadOnly()
    이 추상 적 인 경로 이름 이 지정 한 파일 이나 디 렉 터 리 를 표시 하여 읽 기 동작 만 할 수 있 도록 합 니 다.
    26
    public static File createTempFile(String prefix, String suffix, File directory) throws IOException
    지정 한 디 렉 터 리 에 새 빈 파일 을 만 들 고 주어진 접두사 와 접두사 문자열 로 이름 을 만 듭 니 다.
    27
    public static File createTempFile(String prefix, String suffix) throws IOException
    기본 임시 파일 디 렉 터 리 에 빈 파일 을 만 들 고 주어진 접두사 와 접 두 사 를 사용 하여 이름 을 만 듭 니 다.
    28
    public int compareTo(File pathname)
    알파벳 순 으로 두 추상 적 인 경로 명 을 비교 하 다.
    29
    public int compareTo(Object o)
    알파벳 순 으로 추상 적 인 경로 이름과 주어진 대상 을 비교 합 니 다.
    30
    public boolean equals(Object obj)
    이 추상 적 인 경로 이름과 주어진 대상 이 같 는 지 시험 합 니 다.
    31
    public String toString()
    이 추상 적 인 경로 이름 의 경로 이름 문자열 을 되 돌려 줍 니 다.
    InputStream 바이트 입력 흐름
    package com.gaoji.io;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    //     
    public class IOdome_03 {
        //     InputStream
        public static void main(String[] args) throws IOException   {
            File f1 = new File("D://");//     
            File f2 = new File(f1, "aaa.txt");//    
            
            InputStream in =null;
            try {
                in = new FileInputStream(f2);//          
                int a = 0;//           
    //            in.skip(1);//  n     
    //                 
    //            while ((a=in.read())!=-1) {
    //                System.out.print((char)a);
    //            }
    //               (     ,     )
                byte[] bs = new byte[in.available()];
                while ((a=in.read())!=-1) {
                    for(int i=0;i<bs.length;i++){
                        if(bs[i]==0){
                            break;
                        }
                    }
                    System.out.print((char)a);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                in.close();
            }
        }
    }
    
    

    출력 스 트림 바이트 출력 흐름
    package com.gaoji.io;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    //     
    public class IOdome_04 {
        //     OutputStream
        public static void main(String[] args) throws IOException {
            File f1 = new File("D://");//     
            File f2 = new File(f1, "aaa.txt");//    
            OutputStream out=null;
            try {
                out=new FileOutputStream(f2,true);//true   ,false   
                String a="holle wrold1";
    //                     
    //            byte[] bs=a.getBytes();
    //            for (int i = 0; i < bs.length; i++) {
    //                out.write(bs[i]);
    //            }
    //                  
                out.write(a.getBytes());
            } catch (Exception e) {
                // TODO: handle exception
            }finally {
                out.flush();//  (         ,       )
                out.close();//  
            } 
        }
    }
    

    리더 문자 입력 흐름
    // 
        public static void reader() {
            try {
                InputStreamReader fr=new InputStreamReader(new FileInputStream(new File("D:\\aaa.txt")),"utf-8");
                char[] cs=new char[6];
                fr.read(cs);
                System.out.println(new String(cs));
                System.out.println(fr.getEncoding());
                fr.close();
        } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
            
        }
    

    Writer 문자 출력 흐름
    바이트 출력 흐름 을 사용 하면 파일 흐름 을 새로 고치 지 않 고 시스템 이 자동 으로 새로 고침 되 며 문자 출력 흐름 이 다 릅 니 다. 새로 고침 하지 않 고 닫 으 면 파일 이 작 동 하지 않 습 니 다.
    // 
        public static void writer() {
            OutputStreamWriter ows = null;
            try {
                ows = new OutputStreamWriter(new FileOutputStream(new File("D://aaa.txt")), "gbk");
                String a = "      ";
                ows.write(a);
                System.out.println(ows.getEncoding());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    ows.flush();
                    ows.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    

    직렬 화 와 반 직렬 화
  • User. java 사용자 실체 클래스
  • package com.gaoji.io;
    
    import java.io.Serializable;
    //IO       Serializable
    public class User implements Serializable {
    
        /**
         *      id
         * transient //             
         */
        private static final long serialVersionUID = 4950216177746797393L;
        private int id;
        private String name;
        private char sex;
        private transient String phone;
        public User(int id, String name, char sex, String phone) {
            super();
            this.id = id;
            this.name = name;
            this.sex = sex;
            this.phone = phone;
        }
        public User() {
            super();
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public char getSex() {
            return sex;
        }
        public void setSex(char sex) {
            this.sex = sex;
        }
        public String getPhone() {
            return phone;
        }
        public void setPhone(String phone) {
            this.phone = phone;
        }
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", phone=" + phone + "]";
        }
    }
    
    
  • Run. java 직렬 화 운행 클래스
  • package com.gaoji.io;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    //           
    public class IOdome_07 {
    
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            xlh();
            fxlh();
    
        }
        //     
        public static void xlh() throws FileNotFoundException, IOException {
            User u = new User(1, "  ", ' ', "15665620000");
            ObjectOutputStream out = null;
            try {
                out = new ObjectOutputStream(new FileOutputStream(new File("d:\\user.dat")));
                out.writeObject(u);
                System.out.println(u);
            } finally {
                out.flush();//  
                out.close();//  
            }
        }
        //      
        public static void fxlh() throws IOException, ClassNotFoundException {
            ObjectInputStream in = null;
            try {
                in = new ObjectInputStream(new FileInputStream(new File("d:\\user.dat")));
                User u = (User) in.readObject();
                System.out.println(u.toString());
            } finally {
                in.close();
            }
        }
    
    }
    
    

    파일 흐름 복사
  • 바이트 흐름 실현
  • //    FileInputStream FileOutputStream  
        public static void InputOutputStream() throws IOException {
            File f1 = new File("D://");
            File f2 = new File(f1, "qqq.jpg");
    
            File f3 = new File("C://");
            File f4 = new File(f3, "qqq.jpg");
    
            FileInputStream fis = new FileInputStream(f2);//   (  )
            FileOutputStream fos = new FileOutputStream(f4);//   (  )
            int len = 0;
            while ((len = fis.read()) != -1) {
                fos.write(len);
            }
            fos.flush();
            fos.close();
            fis.close();
        }
    
  • 문자 흐름 실현
  • //      BufferedInputStream BufferedOutputStream  
        public static void BufferedInputOutputStream() throws IOException {
            // TODO Auto-generated method stub
            File f1 = new File("D://");
            File f2 = new File(f1, "qqq.jpg");
            File f3 = new File("C://");
            File f4 = new File(f3, "qqq.jpg");
            BufferedInputStream bin = null;
            BufferedOutputStream out = null;
            try {
                byte[] bs = new byte[1024];
                bin = new BufferedInputStream(new FileInputStream(f2));
                out = new BufferedOutputStream(new FileOutputStream(f4));
                while (bin.read(bs) != -1) {
                    out.write(bs);
                }
            } catch (Exception e) {
                // TODO: handle exception
            } finally {
                bin.close();
                out.flush();
                out.close();
            }
        }
    

    IO 흐름 은 시스템 디스크 의 모든 파일 을 재 귀적 으로 찾 습 니 다.
    package com.gaoji.io;
    
    import java.io.File;
    
    public class IOdomemy_01 {
       public static void main(String[] args) {
        //File f = new File("D://");
        File f = new File("D:\\");
        //getFile(f);
    }
        //                 
        public static void getFile(File f) {
            File[] fs = f.listFiles();
            if(fs != null && fs.length !=0){
                for(File f1:fs){
                    if(f1.isDirectory()){
                        getFile(f1);
                    }else{
                        System.out.println(f1.getName());
                    }
                }
            }
        }
    }
    
    

    시험 문제 가 공고 하 다.
    1. 디스크 루트 디 렉 터 리 에 a. txt 파일 을 새로 만 들 고 파일 에 임의의 내용 을 입력 합 니 다.
    package com.gaoji.io;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    //1. d        a.txt   ,          
    public class IOword_01 {
        public static void main(String[] args) {
            dome0111();
        }
        // createTempFile    
        public static void dome01(){
            File parent=new File("d:"+File.separator); 
            try {
                File file = parent.createTempFile("hjbqq",".txt",parent);
                System.out.println(file);
                //d:\hjbqq1465893390880583617.txt
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
         createNewFile    
        public static void dome011(){
            File f1=new File("d:"+File.separator);
            File f2=new File(f1,"txt.txt");
            try {
                // txt.txt    , ,   
                f2.createNewFile();
                System.out.println("    :"+f2.exists());
                System.out.println(f2);
                //d:\txt.txt
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //     
        public static void dome0111(){
            File f1=new File("d:"+File.separator);
            File f2=new File(f1,"txt.txt");
            try {
                FileWriter fw = new FileWriter(f2);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write("    ");
                bw.flush();//     
                
                bw.close();
                fw.close();
                System.out.println("    ");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        }
    }
    
    

    2. txt. txt 파일 크기 읽 기, 최근 접근 시간, 디 렉 터 리 여부.이 파일 삭제
    package com.gaoji.io;
    
    import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    //  txt.txt    ,      ,       。      
    public class IOword_02 {
        public static void main(String[] args) {
            dome1();
        }
    
        public static void dome1() {
            File f1 = new File("D:"+File.separator);
            File f2 = new File(f1,"txt.txt");
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd  HH:mm:ss");
            
            System.out.println(f2);
            System.out.println(f2+"      "+f2.length());
            System.out.println(f2+"           "+sdf.format(new Date(f2.lastModified())));
            System.out.println(f2+"       :"+f2.isDirectory());
            if(f2.delete()){
                System.out.println("    !!");
            }else{
                System.out.println("    ");
            }
        }
    }
    
    

    3. 이 폴 더 의 모든 파일 을 삭제 하 는 프로그램 을 만 듭 니 다. (재 귀적 알고리즘 으로 구현)
    package com.gaoji.io;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class IOword_03 {
    
        //          ,             ,
        //      ,             (        )
        public static void main(String[] args) throws IOException {
            File f1=new File("d:"+File.separator);
            File f2 = new File(f1,"txt");
            
            getFile(f2);
    
        }
        //          
        public static void getFile(File f) {
            File[] fs = f.listFiles();
            if(fs != null && fs.length !=0){
                for(File f1:fs){
                    if(f1.isDirectory()){
                        getFile(f1);
                    }else{
                       f1.delete();
                    }
                }
            }
        }
    }
    
    

    자원 다운로드

    좋은 웹페이지 즐겨찾기