Java File IO学习笔记

声明:以下转载自:Java中的File文件类详解

文件操作在Java的io操作中占有十分重要的地位,本文从以下几个方面来接受Java中对文件的操作。

1.Java中新建或者删除一个文件,文件夹以及createNewFile(),delete(),mkdir(),mkdirs()函数的使用。

2. 判断文件的函数:exists(),isFile(),isAbsolute(),isDirectory(),canRead(),canWrite(),isHidden()函数的使用。

3.
文件属性的函数:lastModified(),length(),list(),listFiles(),renameTo(),getName(),getParent(),getPath(),getAbsolutePath(),delete()函数的使用。

4. 文件输入输出操作中的FileInputStream(),InputStreamReader()的使用和差别。

一:创建一个文件或者文件夹:


public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("D:/hust/file.txt");
        File directory = new File("D:/hust/hk");
        File dir = new File("D:/hank/hu/file.txt");
        if (!directory.exists()) {
            System.out.println(directory.mkdir());
        }
        if (!dir.exists()) {
            System.out.println(dir.mkdirs());
        }
        if (!file.exists()) {
            System.out.println(":" + file.createNewFile());
        }
    }
}

上面介绍了创建文件,以及创建文件夹的两种方式。首先是创建文件:

在D盘的hust的目录下面新建一个file.txt文件,通过exist()来判断文件是否已经存在,如果文件不存在调用createNewFile(),CreateNewFile()返回一个Boolean值,如果指定的文件不存在并成功地创建,则返回
true;如果指定的文件已经存在,则返回 false。

创建文件夹如果指定的文件夹不存在可以通过mkdir(),mkdirs()来创建文件夹。

mkdir(),和mkdirs()都返回一个Boolean值,如果指定文件夹不存在并且通过mkdir()或者mkdirs()创建成功则返回一个true 值否则返回false。

mkdir(),和mkdirs()的区别是如果新建的文件目录的上级目录不存在则mkdir()回报异常不能成功创建文件夹,而mkdirs(),会将目录与上级目录一起创建。

二:判断文件属性的函数:

exists()判断文件是否存在如果不存在则返回一个true,否则返回一个false。isFile()和isDirectory()分别用于判断是不是文件和是不是文件夹,canRead(),canWrite(),isHidden(),分别用于判断文件是否可读,可写,是否隐藏。

public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("D:/hust/file.txt");
        File directory = new File("D:/hust/hk");
        File dir = new File("D:/hank/hu/file.txt");
        if (!directory.exists()) {
            System.out.println(directory.mkdir());
        }
        if (!dir.exists()) {
            System.out.println(dir.mkdirs());
        }
        if (!file.exists()) {
            System.out.println(":" + file.createNewFile());
        }
        file.setReadable(true);
        file.setWritable(false);
        System.out.println("isFile:"+file.isFile()+"\tisDirectory:"+file.isDirectory()+"\tcanRead:"+file.canRead()+"\tcanWrite:"+file.canWrite());
        System.out.println(dir.isFile()+":"+dir.isDirectory());
    }
}

输出结果如下:

isFile:true isDirectory:false

canRead:true canWrite:false

isFile:false isDirectory:true

三:文件属性的函数

:lastModified(),length(),list(),listFiles(),renameTo(),getName(),getParent(),getPath(),getAbsolutePath()函数的使用。

public class FileTest {
    public static void main(String[] args) throws IOException {
        File dir = new File("D:/hust");
        String[] str=dir.list();
        File[] str1=dir.listFiles();
        System.out.println("lastModified():"+new Date(dir.lastModified()));
        System.out.println("length():"+dir.length()+"\ngetAbsolutePath:"+dir.getAbsolutePath());
        System.out.println("getPath:"+dir.getPath());
        System.out.println("getName:"+dir.getName()+"\ngetParent:"+dir.getParent());
        for(int j=0;j<str1.length;j++)
            System.out.println(":"+str1[j]);
        for(int i=0;i<str.length;i++)
        {
            System.out.println(":"+str[i]);
        }
    }
}

输出结果:

lastModified():Mon Aug 01 22:01:15 CST 2016

length():0

getAbsolutePath:D:\hust

getPath:D:\hust

getName:hust

getParent:D:\

:D:\hust\file.txt

:D:\hust\hank

:D:\hust\hk

:D:\hust\king

:file.txt

:hank

:hk

:king

lastModified()函数返回一个long类型的值,上面的类子中通过Date函数将long类型的值转化为了日期。getAbsolutePath()返回目录的绝对路径。最重要的两个方法是list(),和listFiles(),list()是返回目录下面所有的目录或文件的名称,返回的是一个字符串数组。而listFiles()返回的是目录下面的文件和目录数组,返回的是文件和目录的绝对路径。

Delete()的用法,如何删除一个文件和删除一个文件夹。

删除一个文件比较简单,直接判断文件是否存在,如果存在的话就删除,如果文件不存在可以不用操作。但是删除一个文件夹比较麻烦,我们不能够直接的删除一个文件夹,删除文件夹时必须保证该文件夹为空,也就是说文件夹里面的文件和文件夹要全部被删除之后才能够删除该文件夹。下面是实例:

public class FileTest {
    public static void main(String[] args) throws IOException {
        deleteFiles("D:/Xiaomi");
    }
    public static void deleteFiles(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (file.isFile()) {
            file.delete();
        } else if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File myfile : files) {
                System.out.println(":" + myfile.getAbsolutePath());
                deleteFiles(myfile.getAbsolutePath());
            }
            file.delete();
        }
    }
}

上面的D:/xiaomi是一个文件夹,它的下面还有其他的文件夹与文件,如果直接调用delete()函数的话,是删除不了的。因此利用递归的算法先删除其里面的文件和文件夹,在删除D:/xiaomi就可以了。

四:文件输入输出操作中的FileInputStream(),InputStreamReader()的使用和差别。

FileInputStream ()是使用字节方式输入,InputStreamReader()字符方式输入。一般字节方式输入用来处理图片,声音,图像等二进制流。

public class FileTest {
    public static void main(String[] args) throws IOException {
        // deleteFiles("D:/Xiaomi");
        System.out.println(":" + ReadFileByByte("D:/File1/心理健康常识.txt"));
        System.out.println(":" + ReadFileByChar("D:/File1/心理健康常识.txt"));
    }

    public static String ReadFileByByte(String filepath)
            throws FileNotFoundException {
        File file = new File(filepath);
        StringBuffer sb = new StringBuffer();
        if (!file.exists() || !file.isFile()) {
            System.out.println("this file is not exist!");
            return null;
        }
        FileInputStream fileinputstream = new FileInputStream(file);
        byte[] temp = new byte[1024];
        try {
            while (fileinputstream.read(temp) != -1) {
                sb.append(new String(temp));

            }
            fileinputstream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // System.out.println(":"+sb.length());
        return sb.toString();
    }

    public static String ReadFileByChar(String filepath) {
        File file = new File(filepath);
        if (!file.exists() || !file.isFile()) {
            return null;
        }

        StringBuffer content = new StringBuffer();

        try {
            char[] temp = new char[1024];
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(
                    fileInputStream);
            while (inputStreamReader.read(temp) != -1) {
                content.append(new String(temp));
                temp = new char[1024];
            }

            fileInputStream.close();
            inputStreamReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return content.toString();
    }

别。

声明:以下转载自: Java File类总结和FileUtils类

文件存在和类型判断

  创建出File类的对象并不代表该路径下有此文件或目录。

  用public boolean exists()可以判断文件是否存在。

  File类的对象可以是目录或者文件。

  如果是目录,public boolean isDirectory()返回true;

  如果是文件(非目录则是文件),public boolean isFile()返回true;

  但是注意需要先判断文件是否存在,如果文件不存在,上面两个方法都返回false,即不存在的File类对象既不是文件也不是目录

创建文件

  public boolean createNewFile()会创建一个新的空文件,只有该文件不存在的时候会创建,如果文件已经存在的话则返回false。

创建文件夹

  public boolean mkdir()

  创建目录,成功返回true。只能创建一个文件夹,要求所有的父目录都存在,否则创建失败。

  public boolean mkdirs()

  创建目录,成功返回true,会创建所有不存在的父目录。(注意即便最后创建失败,但是也可能创建了一些中间目录)。

  上面两个方法如果要创建的目录已经存在,不再重新创建,都返回false,只有新建目录返回true。

目录操作

  列出目录中的文件有以下方法可选:

  String[] list()

  String[] list(FilenameFilter filter)

  返回文件名数组。

  File[] listFiles()

  File[] listFiles(FileFilter filter)

  File[] listFiles(FilenameFilter filter)

  返回File数组。

  参数是文件或者文件名过滤器。

  注意返回为空和返回为null的意义是不同的。

  若不包含(符合条件的)文件,返回为空。

  但是如果返回为null,则表明调用方法的File对象可能不是一个目录,或者发生了IO错误。

删除文件

  boolean delete()方法会删除文件,如果File对象是文件则直接删除,对于目录来说,如果是空目录则直接删除,非空目录则无法删除,返回false。

  如果要删除的文件不能被删除则会抛出IOException。

  注意:不论是创建文件、创建目录还是删除文件,只有在动作真正发生的时候会返回true。

FileUtils类

  在项目中写一些工具类包装通用操作是很有必要的,看了一下apache的FileUtils类,copy了一些方法出来:

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mengdd.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * FileUtils copied from org.apache.commons.io.FileUtils
 */
public class FileUtils {
    /**
     * Construct a file from the set of name elements.
     *
     * @param directory
     *            the parent directory
     * @param names
     *            the name elements
     * @return the file
     */
    public static File getFile(File directory, String... names) {
        if (directory == null) {
            throw new NullPointerException(
                    "directorydirectory must not be null");
        }
        if (names == null) {
            throw new NullPointerException("names must not be null");
        }
        File file = directory;
        for (String name : names) {
            file = new File(file, name);
        }
        return file;
    }

    /**
     * Construct a file from the set of name elements.
     *
     * @param names
     *            the name elements
     * @return the file
     */
    public static File getFile(String... names) {
        if (names == null) {
            throw new NullPointerException("names must not be null");
        }
        File file = null;
        for (String name : names) {
            if (file == null) {
                file = new File(name);
            }
            else {
                file = new File(file, name);
            }
        }
        return file;
    }

    /**
     * Opens a {@link FileInputStream} for the specified file, providing better
     * error messages than simply calling <code>new FileInputStream(file)</code>
     * .
     * <p>
     * At the end of the method either the stream will be successfully opened,
     * or an exception will have been thrown.
     * <p>
     * An exception is thrown if the file does not exist. An exception is thrown
     * if the file object exists but is a directory. An exception is thrown if
     * the file exists but cannot be read.
     *
     * @param file
     *            the file to open for input, must not be {@code null}
     * @return a new {@link FileInputStream} for the specified file
     * @throws FileNotFoundException
     *             if the file does not exist
     * @throws IOException
     *             if the file object is a directory
     * @throws IOException
     *             if the file cannot be read
     */
    public static FileInputStream openInputStream(File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File ‘" + file
                        + "‘ exists but is a directory");
            }
            if (file.canRead() == false) {
                throw new IOException("File ‘" + file + "‘ cannot be read");
            }
        }
        else {
            throw new FileNotFoundException("File ‘" + file
                    + "‘ does not exist");
        }
        return new FileInputStream(file);
    }

    /**
     * Opens a {@link FileOutputStream} for the specified file, checking and
     * creating the parent directory if it does not exist.
     * <p>
     * At the end of the method either the stream will be successfully opened,
     * or an exception will have been thrown.
     * <p>
     * The parent directory will be created if it does not exist. The file will
     * be created if it does not exist. An exception is thrown if the file
     * object exists but is a directory. An exception is thrown if the file
     * exists but cannot be written to. An exception is thrown if the parent
     * directory cannot be created.
     *
     * @param file
     *            the file to open for output, must not be {@code null}
     * @param append
     *            if {@code true}, then bytes will be added to the
     *            end of the file rather than overwriting
     * @return a new {@link FileOutputStream} for the specified file
     * @throws IOException
     *             if the file object is a directory
     * @throws IOException
     *             if the file cannot be written to
     * @throws IOException
     *             if a parent directory needs creating but that fails
     */
    public static FileOutputStream openOutputStream(File file, boolean append)
            throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File ‘" + file
                        + "‘ exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File ‘" + file
                        + "‘ cannot be written to");
            }
        }
        else {
            File parent = file.getParentFile();
            if (parent != null) {
                if (!parent.mkdirs() && !parent.isDirectory()) {
                    throw new IOException("Directory ‘" + parent
                            + "‘ could not be created");
                }
            }
        }
        return new FileOutputStream(file, append);
    }

    public static FileOutputStream openOutputStream(File file)
            throws IOException {
        return openOutputStream(file, false);
    }

    /**
     * Cleans a directory without deleting it.
     *
     * @param directory
     *            directory to clean
     * @throws IOException
     *             in case cleaning is unsuccessful
     */
    public static void cleanDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            String message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (!directory.isDirectory()) {
            String message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        }

        File[] files = directory.listFiles();
        if (files == null) { // null if security restricted
            throw new IOException("Failed to list contents of " + directory);
        }

        IOException exception = null;
        for (File file : files) {
            try {
                forceDelete(file);
            }
            catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception) {
            throw exception;
        }
    }

    // -----------------------------------------------------------------------
    /**
     * Deletes a directory recursively.
     *
     * @param directory
     *            directory to delete
     * @throws IOException
     *             in case deletion is unsuccessful
     */
    public static void deleteDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            return;
        }

        cleanDirectory(directory);

        if (!directory.delete()) {
            String message = "Unable to delete directory " + directory + ".";
            throw new IOException(message);
        }
    }

    /**
     * Deletes a file. If file is a directory, delete it and all
     * sub-directories.
     * <p>
     * The difference between File.delete() and this method are:
     * <ul>
     * <li>A directory to be deleted does not have to be empty.</li>
     * <li>You get exceptions when a file or directory cannot be deleted.
     * (java.io.File methods returns a boolean)</li>
     * </ul>
     *
     * @param file
     *            file or directory to delete, must not be {@code null}
     * @throws NullPointerException
     *             if the directory is {@code null}
     * @throws FileNotFoundException
     *             if the file was not found
     * @throws IOException
     *             in case deletion is unsuccessful
     */
    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectory(file);
        }
        else {
            boolean filePresent = file.exists();
            if (!file.delete()) {
                if (!filePresent) {
                    throw new FileNotFoundException("File does not exist: "
                            + file);
                }
                String message = "Unable to delete file: " + file;
                throw new IOException(message);
            }
        }
    }

    /**
     * Deletes a file, never throwing an exception. If file is a directory,
     * delete it and all sub-directories.
     * <p>
     * The difference between File.delete() and this method are:
     * <ul>
     * <li>A directory to be deleted does not have to be empty.</li>
     * <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
     * </ul>
     *
     * @param file
     *            file or directory to delete, can be {@code null}
     * @return {@code true} if the file or directory was deleted, otherwise
     *         {@code false}
     *
     */
    public static boolean deleteQuietly(File file) {
        if (file == null) {
            return false;
        }
        try {
            if (file.isDirectory()) {
                cleanDirectory(file);
            }
        }
        catch (Exception ignored) {
        }

        try {
            return file.delete();
        }
        catch (Exception ignored) {
            return false;
        }
    }

    /**
     * Makes a directory, including any necessary but nonexistent parent
     * directories. If a file already exists with specified name but it is
     * not a directory then an IOException is thrown.
     * If the directory cannot be created (or does not already exist)
     * then an IOException is thrown.
     *
     * @param directory
     *            directory to create, must not be {@code null}
     * @throws NullPointerException
     *             if the directory is {@code null}
     * @throws IOException
     *             if the directory cannot be created or the file already exists
     *             but is not a directory
     */
    public static void forceMkdir(File directory) throws IOException {
        if (directory.exists()) {
            if (!directory.isDirectory()) {
                String message = "File " + directory + " exists and is "
                        + "not a directory. Unable to create directory.";
                throw new IOException(message);
            }
        }
        else {
            if (!directory.mkdirs()) {
                // Double-check that some other thread or process hasn‘t made
                // the directory in the background
                if (!directory.isDirectory()) {
                    String message = "Unable to create directory " + directory;
                    throw new IOException(message);
                }
            }
        }
    }

    /**
     * Returns the size of the specified file or directory. If the provided
     * {@link File} is a regular file, then the file‘s length is returned.
     * If the argument is a directory, then the size of the directory is
     * calculated recursively. If a directory or subdirectory is security
     * restricted, its size will not be included.
     *
     * @param file
     *            the regular file or directory to return the size
     *            of (must not be {@code null}).
     *
     * @return the length of the file, or recursive size of the directory,
     *         provided (in bytes).
     *
     * @throws NullPointerException
     *             if the file is {@code null}
     * @throws IllegalArgumentException
     *             if the file does not exist.
     *
     */
    public static long sizeOf(File file) {

        if (!file.exists()) {
            String message = file + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (file.isDirectory()) {
            return sizeOfDirectory(file);
        }
        else {
            return file.length();
        }

    }

    /**
     * Counts the size of a directory recursively (sum of the length of all
     * files).
     *
     * @param directory
     *            directory to inspect, must not be {@code null}
     * @return size of directory in bytes, 0 if directory is security
     *         restricted, a negative number when the real total
     *         is greater than {@link Long#MAX_VALUE}.
     * @throws NullPointerException
     *             if the directory is {@code null}
     */
    public static long sizeOfDirectory(File directory) {
        checkDirectory(directory);

        final File[] files = directory.listFiles();
        if (files == null) { // null if security restricted
            return 0L;
        }
        long size = 0;

        for (final File file : files) {

            size += sizeOf(file);
            if (size < 0) {
                break;

            }

        }

        return size;
    }

    /**
     * Checks that the given {@code File} exists and is a directory.
     *
     * @param directory
     *            The {@code File} to check.
     * @throws IllegalArgumentException
     *             if the given {@code File} does not exist or is not a
     *             directory.
     */
    private static void checkDirectory(File directory) {
        if (!directory.exists()) {
            throw new IllegalArgumentException(directory + " does not exist");
        }
        if (!directory.isDirectory()) {
            throw new IllegalArgumentException(directory
                    + " is not a directory");
        }
    }

}

参考资料

  File类官方文档:

  http://docs.oracle.com/javase/7/docs/api/java/io/File.html

  org.apache.commons.io.FileUtils源码:

  http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/2.4/org/apache/commons/io/FileUtils.java

  本博客旧博文:

  Java IO File类

  Java IO 用递归实现目录删除和树形目录展示 Java实现

原文地址:https://www.cnblogs.com/xiaonihao444/p/8763226.html

时间: 2024-12-04 12:35:55

Java File IO学习笔记的相关文章

Java File类学习笔记4:自定义一个类,过滤指定扩展名的文件

自定义一个类,继承FileNameFilter类,获得某一目录下所有指定扩展名的文件. 方法一: /** * 说明: * 自定义FilterByJava类,过滤指定扩展名的文件 * */ import java.io.File; import java.io.FilenameFilter; public class FilterByJava implements FilenameFilter{ private String ext; public FilterByJava(String ext)

Java File类学习笔记2:File类对象及常用操作方法

一. 文件.相对路径与绝对路径 1.文件 (1)标准文件:就像图片,音乐文件等. (2)目录文件:也就是平常所说的文件夹. (3)虚拟内存文件:系统在运行程序时生成的临时性文件. 2.文件的路径 (1)相对路径:相对于某一文件的路径,形象地说是把两文件的绝对路径相同的部分砍掉,剩下的就是相对路径 如: A文件是"D:\MyDocuments\StudySample\src\cn\xmh", B文件是"D:\MyDocuments\StudySample\src\netjava

Java IO学习笔记:概念与原理

Java IO学习笔记:概念与原理 一.概念 Java中对文件的操作是以流的方式进行的.流是Java内存中的一组有序数据序列.Java将数据从源(文件.内存.键盘.网络)读入到内存 中,形成了流,然后将这些流还可以写到另外的目的地(文件.内存.控制台.网络),之所以称为流,是因为这个数据序列在不同时刻所操作的是源的不同部分. 二.分类 流的分类,Java的流分类比较丰富,刚接触的人看了后会感觉很晕.流分类的方式很多: 1.按照输入的方向分,输入流和输出流,输入输出的参照对象是Java程序. 2.

java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)

java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessController的checkPerssiom方法,访问控制器AccessController的栈检查机制又遍历整个 PerssiomCollection来判断具体拥有什么权限一旦发现栈中一个权限不允许的时候抛出异常否则简单的返回,这个过程实际上比我的描述要复杂 得多,这里我只是简单的一句带过,因为这

java之jvm学习笔记五(实践写自己的类装载器)

java之jvm学习笔记五(实践写自己的类装载器) 课程源码:http://download.csdn.net/detail/yfqnihao/4866501 前面第三和第四节我们一直在强调一句话,类装载器和安全管理器是可以被动态扩展的,或者说,他们是可以由用户自己定制的,今天我们就是动手试试,怎么做这部分的实践,当然,在阅读本篇之前,至少要阅读过笔记三. 下面我们先来动态扩展一个类装载器,当然这只是一个比较小的demo,旨在让大家有个比较形象的概念. 第一步,首先定义自己的类装载器,从Clas

java/android 设计模式学习笔记(一)---单例模式

前段时间公司一些同事在讨论单例模式(我是最渣的一个,都插不上嘴 T__T ),这个模式使用的频率很高,也可能是很多人最熟悉的设计模式,当然单例模式也算是最简单的设计模式之一吧,简单归简单,但是在实际使用的时候也会有一些坑. PS:对技术感兴趣的同鞋加群544645972一起交流 设计模式总目录 java/android 设计模式学习笔记目录 特点 确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例. 单例模式的使用很广泛,比如:线程池(threadpool).缓存(cache).对

java/android 设计模式学习笔记(7)---装饰者模式

这篇将会介绍装饰者模式(Decorator Pattern),装饰者模式也称为包装模式(Wrapper Pattern),结构型模式之一,其使用一种对客户端透明的方式来动态的扩展对象的功能,同时它也是继承关系的一种替代方案之一,但比继承更加灵活.在现实生活中也可以看到很多装饰者模式的例子,或者可以大胆的说装饰者模式无处不在,就拿一件东西来说,可以给它披上无数层不一样的外壳,但是这件东西还是这件东西,外壳不过是用来扩展这个东西的功能而已,这就是装饰者模式,装饰者的这个角色也许各不相同但是被装饰的对

【DAY12】第十二天集合&泛型&IO学习笔记

hash:散列 ------------------ Hashset集合内部是通过HashMap进行实现的.使用的是HashMap中key部分. 对象在添加进集合中时,首选会对hashcode进行处理(hashcode右移16位和 自身做异或运算)得到一个经过处理的hash值,然后该值和集合的容量进行 &运算,得到介于0和集合容量值之间一个数字.该数字表示着数组的下标. 也就是该元素应该存放在哪个元素中. Map与Collection -------------- Map与Collection在

java之jvm学习笔记十三(jvm基本结构)

java之jvm学习笔记十三(jvm基本结构) 这一节,主要来学习jvm的基本结构,也就是概述.说是概述,内容很多,而且概念量也很大,不过关于概念方面,你不用担心,我完全有信心,让概念在你的脑子里变成图形,所以只要你有耐心,仔细,认真,并发挥你的想象力,这一章之后你会充满自信.当然,不是说看完本章,就对jvm了解了,jvm要学习的知识实在是非常的多.在你看完本节之后,后续我们还会来学jvm的细节,但是如果你在学习完本节的前提下去学习,再学习其他jvm的细节会事半功倍. 为了让你每一个知识点都有迹