JAVA面試【JAVA基礎系列-1-17】【更新於2019/05/18】

【轉載自:https://mp.weixin.qq.com/s/KnSUprd6Z7zbpZAVR1OEdwhttps://www.cnblogs.com/cocoxu1992/p/10460251.html

基礎題

1.JDK和JRE有什麼區別?

答:JDK,全稱:java development kit,中文名:JAVA開發工具,JDK裏面包含有JRE,我們一般都是安裝JDK,安裝好之後還需要進行環境變量的配置(具體配置過程看:https://blog.csdn.net/qq_34584694/article/details/79448222

        JRE,全稱:java runtime environment,中文名:JAVA運行環境,可以理解爲JAVA運行的承載容器,

2.==和equals的區別是什麼?

答:== :對於基本數據類型(byte,short,char,int,long,float,double)是比較值是否相同

       == :對於引用數據類型(String,Integer,date),比較兩個堆內存地址值(hashCode())是否相同

       equals:不適用於基本數據類型,其默認比較兩個堆內存地址值是否相同,但是可以對其的方法進行重寫【敲黑板,劃重點:當重寫了equals()方法時,請務必重寫hashCode()方法,具體請看第三點】

原生Object中的equals()方法:

       在這裏說明了該方法的幾種情況,我寫在下方的代碼註釋裏面了

/**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     * <ul>
     * <li>It is <i>reflexive</i>: for any non-null reference value
     *     {@code x}, {@code x.equals(x)} should return
     *     {@code true}.

     *     反射性:對於不爲null的參考值x,調用x.equals(x)時,需要返回true

     * <li>It is <i>symmetric</i>: for any non-null reference values
     *     {@code x} and {@code y}, {@code x.equals(y)}
     *     should return {@code true} if and only if
     *     {@code y.equals(x)} returns {@code true}.

     *     對稱性:對於不爲null的參考值x和y,如果調用x.equals(y)時返回true,則y.equals(x)也需 
     *     要返回true

     * <li>It is <i>transitive</i>: for any non-null reference values
     *     {@code x}, {@code y}, and {@code z}, if
     *     {@code x.equals(y)} returns {@code true} and
     *     {@code y.equals(z)} returns {@code true}, then
     *     {@code x.equals(z)} should return {@code true}.

     *     傳遞性:對於不爲null的參考值x,y,z,如果調用x.equals(y)和y.equals(z)都返回true時, 
     *     那麼x.equals(z)也需要返回true

     * <li>It is <i>consistent</i>: for any non-null reference values
     *     {@code x} and {@code y}, multiple invocations of
     *     {@code x.equals(y)} consistently return {@code true}
     *     or consistently return {@code false}, provided no
     *     information used in {@code equals} comparisons on the
     *     objects is modified.

     *     一致性:對於不爲null的參考值x和y,在對象沒有被修改時,即使多次調用x.equals(y)都應該 
     *     同樣的返回true或false


     * <li>For any non-null reference value {@code x},
     *     {@code x.equals(null)} should return {@code false}.
 
     *     對於不爲null的參考值x,調用x.equals(null)應該返回false
     * </ul>
     * <p>
     * The {@code equals} method for class {@code Object} implements
     * the most discriminating possible equivalence relation on objects;
     * that is, for any non-null reference values {@code x} and
     * {@code y}, this method returns {@code true} if and only
     * if {@code x} and {@code y} refer to the same object
     * ({@code x == y} has the value {@code true}).
     * <p>
     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.
     *
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} if this object is the same as the obj
     *          argument; {@code false} otherwise.
     * @see     #hashCode()
     * @see     java.util.HashMap
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

String重寫的equals()方法:

       描述:將這個字符串對象和指定對象進行比較,當該對象不爲null,是字符串對象且字符的序列和指定對象完全一樣時,結果爲true,其他情況都爲false

       在代碼上,我們也可以看出該重寫的方法是對兩個對象的內容進行比較,而不是默認的比較對象的堆地址

/**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

Integer重寫的equals()方法:

  描述:將這個對象和指定的特殊對象進行比較,當該對象不爲null,是Integer類型且內容和指定對象的內容一致時,結果爲true,其他情況都爲false

  在代碼上看,Integer重寫的equald()方法是對兩個對象的內容進行比較的,而不是對其堆地址進行比較

/**
     * Compares this object to the specified object.  The result is
     * {@code true} if and only if the argument is not
     * {@code null} and is an {@code Integer} object that
     * contains the same {@code int} value as this object.
     *
     * @param   obj   the object to compare with.
     * @return  {@code true} if the objects are the same;
     *          {@code false} otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

Date重寫的equals()方法:

描述:比較兩個時間是否相等,當對象不爲null且是時間對象,精確到毫秒的時間點是一樣的時候,返回true,其他情況都返回false,因此,兩個時間對象進行比較,其getTime()方法返回同樣的long類型的值

/**
     * Compares two dates for equality.
     * The result is <code>true</code> if and only if the argument is
     * not <code>null</code> and is a <code>Date</code> object that
     * represents the same point in time, to the millisecond, as this object.
     * <p>
     * Thus, two <code>Date</code> objects are equal if and only if the
     * <code>getTime</code> method returns the same <code>long</code>
     * value for both.
     *
     * @param   obj   the object to compare with.
     * @return  <code>true</code> if the objects are the same;
     *          <code>false</code> otherwise.
     * @see     java.util.Date#getTime()
     */
    public boolean equals(Object obj) {
        return obj instanceof Date && getTime() == ((Date) obj).getTime();
    }

3.兩個對象的hashCode()相同,則equals()也一定爲true,對嗎?

  答:hashCode()相同時,equals()不一定相同;

         equals()相同時,hashCode()一定相同,前提是重寫hashCode()方法,不然可能會出現不相等的情況。

  描述:返回該對象的hash code值,該方法的支持是由hash tables提供的,比如由java.util.HashMap提供

  hashCode有一些常規的規定:

  1.在JAVA應用程序區間,不管調用了幾次同一個對象,都應該返回同一個正整數,前提是在equals()方法中的對象的信息沒有進行修改。當從一個程序一次運行到相同程序的另一次運行,該整數值(即hashCode)不需要保持一致。

  2.如果有兩個對象通過調用equals()方法判定這兩個對象是相同的,則調用hashCode()方法時,必須返回相同的整數。

  3.如果有兩個對象通過調用equals(java.lang.Object)方法判定這兩個對象是不相等的,則這兩個對象調用hashCode()方法時不要求必須爲每個對象生成截然不同的hashCode,然而程序員應該意識到,爲不同的對象生成截然不同的hashCode可以改善hash table的性能。

/**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code equals} comparisons on the object is modified.
     *     This integer need not remain consistent from one execution of an
     *     application to another execution of the same application.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code hashCode} method on each of the
     *     two objects must produce distinct integer results.  However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java<font size="-2"><sup>TM</sup></font> programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    public native int hashCode();

4.final在java中有什麼作用?

答:修飾類時,表示該類不能夠被繼承;修飾方法時,表示該方法不能夠被重寫;修飾變量時,表示該變量不能夠被修改並且按照JAVA開發規範,被final修飾的變量應該大寫

public class Person {
    private String name = "tom";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
/**
 * final修飾變量
 */
public class Test {
    private final String NAME1 = "name1";   //定義時賦值
    private final String NAME2;     //構造器賦值
    Test (){
        NAME2 = "name2";
    }
    private final String NAME3;      //非靜態塊賦值
    {
        NAME3 = "name3";
    }
    //當變量爲一個對象時,使用final修飾只是說明該對象不能指向其他對象,但是對象中的值是可以被修改的
    private final Person person = new Person();
    public void main(String args[]){
        System.out.println("修改前:"+person.getName());
        person.setName("Jack");
        System.out.println("修改後:"+person.getName());
    }
}

5.java中的Math.round(-1.5)等於多少?

答:-1

Math常用的幾個函數【具體可以參考:java.lang.Math】:

public class Test {
    public static void main(String args[]){
        System.out.println("取最接近的參數"+Math.round(-1.5));
        System.out.println("取絕對值"+Math.abs(-1.5));
        System.out.println("向上取整"+Math.ceil(-1.5));
        System.out.println("向下取整"+Math.floor(-1.5));
        System.out.println("三角函數:sin30 = "+Math.sin(Math.PI/6)+";cos30 = "+Math.cos(Math.PI/6)+";tan30 = "+Math.tan(Math.PI/6));
        System.out.println("取兩個數的最大值:"+Math.max(-1.5,1.5));
        System.out.println("取兩個數的最小值:"+Math.min(-1.5,1.5));
        System.out.println("返回第一個參數的第二個參數冪的值:"+Math.pow(10,2));
    }
}

6.String屬於基礎的數據類型嗎?

答:不是,基本數據類型只有八種,分別是:byte,short,chart,int,long,float,double以及boolean,打開JDK API(如下圖),我們可以看到String是java.lang.*;包下的一個JAVA類,且該類是被final關鍵字所修飾的,不能夠被繼承,所以String不是基礎的數據類型,而是引用數據類型,當然JAVA中除了基本數據類型、引用數據類型之外,還有一個枚舉類型,具體怎樣這裏就不說了,有興趣瞭解的可以去百度。

String常用的方法:【這裏列舉了幾個,具體參考:java.lang.String;包】

1. 初始化一個新創建的 String 對象,它表示一個空字符序列。【構造方法】
    /**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     */
    public String() {
        this.value = new char[0];
    }
2. 通過比較兩個字符串的字母順序來判斷兩個字符串是否一樣,這個比較是基於每個字符的Unicode值進行比較的,字典的字符在對象的字符之前,返回負整數,之後返回正整數,若相等,返回0
   【該方法區分大小寫的】
     /**
     * Compares two strings lexicographically.
    public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }
   【該方法是不區分大小寫的】
    /**
     * Compares two strings lexicographically, ignoring case
     * differences. This method returns an integer whose sign is that of
     * calling <code>compareTo</code> with normalized versions of the strings
     * where case differences have been eliminated by calling
     * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
     * each character.
     * <p>
     * Note that this method does <em>not</em> take locale into account,
     * and will result in an unsatisfactory ordering for certain locales.
     * The java.text package provides <em>collators</em> to allow
     * locale-sensitive ordering.
     *
     * @param   str   the <code>String</code> to be compared.
     * @return  a negative integer, zero, or a positive integer as the
     *          specified String is greater than, equal to, or less
     *          than this String, ignoring case considerations.
     * @see     java.text.Collator#compare(String, String)
     * @since   1.2
     */
    public int compareToIgnoreCase(String str) {
        return CASE_INSENSITIVE_ORDER.compare(this, str);
    }
3.  將這個字符串對象和指定的對象進行比較,只有當該對象不爲空,且是字符串對象,字符序列一致時,才返回true,其他情況都返回false,從下面方法的代碼,我們也可以看到,先是判斷參數是否爲空,然後判斷是否爲String對象,當前面兩個條件都滿足時,在對兩個字符串對象的每個字符進行遍歷
    /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
4.  獲取某個字符在字符串中第一次出現的索引,該方法是指定從0開始查找,沒有找到返回-1
    public int indexOf(int ch) {
        return indexOf(ch, 0);
    }
    獲取某個字符在字符串中第一次出現的索引,可以自己指定從第幾個開始查找,若指定的索引fromIndex小於0,則fromIndex=0,若索引fromIndex大於字符串的最大長度,則返回-1,沒有找到返回-1
    public int indexOf(int ch, int fromIndex) {
        final int max = value.length;
        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= max) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return indexOfSupplementary(ch, fromIndex);
        }
    }
    與上面兩個相反的情況,這裏就不細說了,跟上面兩個情況差不多,只是一個是第一次,一個是最後一次
    public int lastIndexOf(int ch) {
        return lastIndexOf(ch, value.length - 1);
    }
    public int lastIndexOf(int ch, int fromIndex) {
        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            int i = Math.min(fromIndex, value.length - 1);
            for (; i >= 0; i--) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return lastIndexOfSupplementary(ch, fromIndex);
        }
    }
5.  這個方法,特別常用,返回字符串的長度,就是獲取該字符串中的16位Unicode字符數
    /**
     * Returns the length of this string.
     * The length is equal to the number of <a href="Character.html#unicode">Unicode
     * code units</a> in the string.
     *
     * @return  the length of the sequence of characters represented by this
     *          object.
     */
    public int length() {
        return value.length;
    }
6.  將其他類型的對象轉換成字符串對象,返回的是字符串形式的表現
    /**
     * Returns the string representation of the <code>Object</code> argument.
     *
     * @param   obj   an <code>Object</code>.
     * @return  if the argument is <code>null</code>, then a string equal to
     *          <code>"null"</code>; otherwise, the value of
     *          <code>obj.toString()</code> is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

7.java中操作字符串都有哪些類?他們之間有什麼區別?

答:java.lang.String;java.lang.StringBuffer;java.lang.StringBuilder;

區別:String是字符串常量,StringBuffer和StringBuilder是字符串變量

      運行速度:StringBuilder > StringBuffer > String

      線程安全:StringBuffer是線程安全的,StringBuilder是線程不安全的,從下面兩張圖,可以看到StringBuffer類中有使用synchronized關鍵字來保證線程的安全,相反,在StringBuilder類中,不存在synchronized關鍵字

     總結:String:適用於不變的字符串常量操作

               StringBuffer:適用於多線程的情況下操作

               StringBuilder:適用於單線程的情況下操作

8.String str="i"與 String str=new String(“i”)一樣嗎?

9. 如何將字符串反轉?

public class Main {
    //這個在最基礎最基礎的方法了,時間複雜度是O(n),當然還有其他更加有效率方法,比如對半折中的方式等等,想了解的可以自行去百度
    public static void main(String[] args) {
        String str = "nmlkjihgfedcba"; //反過來是abcdefg
        //1.使用split()函數
        String[] arrayList = new String[str.length()];   //定義一個數組
        arrayList = str.split("");      //將字符串拆分成每個字符並放入數組、
        String newStr = "";                     //創建新的字符串變量用來存放新的字符串
        for (int i=arrayList.length-1;i>=0;i--){   //倒序遍歷數組
            newStr += arrayList[i];
        }
        System.out.println("反轉結果:"+newStr);
    }
}

10. String 類的常用方法都有那些?

      具體參考:java.lang.String【上面第六點有解析】

     public String():無參構造方法,用於創建一個新的String對象,而我們最常用的是new String(" "),一個參數的構造方法,【重點:是常量,是常量,是常量】

    /**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     * 創建一個新的String對象,是一個空字符的序列:重點:因爲Strings是不可被修改的,所以沒有必要使 
     * 用這個構造器
     */
    public String() {
        this.value = "".value;
    }

 

11. 抽象類必須要有抽象方法嗎?

抽象類中,既可以有抽象方法,也可以有非抽象方法,並且也可以都沒有

抽象方法只能存在抽象類中,不能存放在非抽象類中,看下圖

12. 普通類和抽象類有哪些區別?

  1. 普通類可以使用new關鍵字來實例化對象,自己的方法自己實現,而抽象類不行,它裏面的抽象方法需要通過子類來實現它,因爲抽象類需要子類來實現,所以抽象類是不能使用private關鍵字修飾的
  2. 普通類中不能有抽象方法,抽象類中既可以有抽象方法,也可以有非抽象方法
  3. 普通方法可以使用public,protected,default,private,抽象方法不能使用private關鍵字

13. 抽象類能使用 final 修飾嗎?

答:不能

解析:這裏我們先來了解一下final關鍵字:final關鍵字能夠修飾:類、方法和變量

       當修飾類時,表示這個類不能夠被繼承,final修飾的類,其成員方法也是被final修飾的;當修飾方法時,表示這個類不能夠被重寫;當修飾變量時,表示該變量的值【基本類型】不能夠被修改或者其引用的地址不能夠被修改【引用類型】

       然後我們現在結合第12點的內容來看,抽象類不能夠自己去實現以及被實例化的,需要子類來實現它,若子類不是抽象類,則必須要實現父抽象類的方法,所以既然抽象類需要子類來實現,如果加了final關鍵字,那何來子類之說呢。

14. 接口和抽象類有什麼區別?

      1. 抽象類跟普通類並沒有太多的區別,部分區別就是不能夠實例化,以及不使用private關鍵字

      2. 接口則完全不能,它不能擁有成員變量且權限默認是public,可以沒必要去修改它

      3. 很重要的一點,JAVA跟C++有一點很不同的就是JAVA是單繼承的,不能夠進行多繼承,所以當某個抽象方法需要多個類去實現時,就需要設計爲接口,讓多個類去實現這個接口,而不是設計成抽象類。

15. java 中 IO 流分爲幾種?

答:

      按照類型/單位來進行區分:字節流[InputStream、OutStream]和字符流[Reader、Write]

      按照方向來進行區分:輸入流[InputStream、Reader]和輸出流[OutStream、Write]

      具體的推薦這篇博客,寫的特別詳細:https://blog.csdn.net/czz1141979570/article/details/80098194

16. Files的常用方法都有哪些?

1.構造器方法  File(String pathname),這裏的pathname參數爲文件的絕對路徑,也就是後面對文件的操作都是在這裏路徑下進行的。從下方的源碼我們也可以看出,這個路徑不能爲空,否則就會報 NullPointerException,填寫的如果是絕對路徑的話,其中的“\”改成“\\”進行轉義。【我們後面寫的方法都以這個方法爲基礎進行】

 /**
     * Creates a new <code>File</code> instance by converting the given
     * pathname string into an abstract pathname.  If the given string is
     * the empty string, then the result is the empty abstract pathname.
     *
     * @param   pathname  A pathname string
     * @throws  NullPointerException
     *          If the <code>pathname</code> argument is <code>null</code>
     */
    public File(String pathname) {
	if (pathname == null) {
	    throw new NullPointerException();
	}
	this.path = fs.normalize(pathname);
	this.prefixLength = fs.prefixLength(this.path);
    }

2.創建新文件方法:public boolean createNewFile() throws IOException:創建一個新的文件,並且僅該文件不存在的時候,從源碼裏我們也可以看到在創建文件之前,會先進行路徑的權限驗證,判斷對該路徑是否有寫入的權限,如果沒有,則返回false,若文件創建成功,則返回true。

/**
     * Atomically creates a new, empty file named by this abstract pathname if
     * and only if a file with this name does not yet exist.  The check for the
     * existence of the file and the creation of the file if it does not exist
     * are a single operation that is atomic with respect to all other
     * filesystem activities that might affect the file.
     * <P>
     * Note: this method should <i>not</i> be used for file-locking, as
     * the resulting protocol cannot be made to work reliably. The 
     * {@link java.nio.channels.FileLock FileLock}
     * facility should be used instead. 
     *
     * @return  <code>true</code> if the named file does not exist and was
     *          successfully created; <code>false</code> if the named file
     *          already exists
     *
     * @throws  IOException
     *          If an I/O error occurred
     *
     * @throws  SecurityException
     *          If a security manager exists and its <code>{@link
     *          java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
     *          method denies write access to the file
     *
     * @since 1.2
     */
    public boolean createNewFile() throws IOException {
	SecurityManager security = System.getSecurityManager();
	if (security != null) security.checkWrite(path);
	return fs.createFileExclusively(path);
    }

        這裏如果對不熟悉的人會有一個疑問,這個方法是無參的,我要怎麼指定新建的文件名?

   答:若使用該方法創建新文件時,需要在new File(路徑+文件名)構造器中指定在哪個路徑下創建什麼格式的文件並叫什麼名字。【可以看下面我自己寫的方法:我在E盤的ideaSpace目錄下,新建一個格式爲txt,名字爲readme的文件】

運行結果截圖:

3.創建文件目錄:public boolean mkdir() 和 public boolean mkdirs(),這裏我沒有給出源碼中的解釋,我用我自己的淺度的理解,來說一下這兩個方法的使用:

 public boolean mkdir() {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkWrite(path);
	}
	return fs.createDirectory(this);
}
public boolean mkdirs() {
	if (exists()) {
	    return false;
	}
	if (mkdir()) {
 	    return true;
 	}
        File canonFile = null;
        try {
            canonFile = getCanonicalFile();
        } catch (IOException e) {
            return false;
        }
	String parent = canonFile.getParent();
        return (parent != null) && 
               (new File(parent, fs.prefixLength(parent)).mkdirs() &&
                                    canonFile.mkdir());
}

        情況一: 我這裏傳入了一個路徑:E:\\ideaSpace\\readme\\abc,其中readme和abc文件夾的不存在的,執行該方法後,mkdir()沒有創建成功,而mkdirs()創建成功了

       情況二:我這裏傳入了一個路徑:E:\\ideaSpace\\readme\\abc,其中abc目錄是不存在的,執行該方法後,mkdir()創建成功,mkdirs()創建失敗

      情況三:【相比於前兩種情況,將mkdir()和mkdirs()的順序對調】我這裏傳入了一個路徑:E:\\ideaSpace\\readme\\abc,其中readme和abc文件夾的不存在的,執行該方法後,mkdir()沒有創建成功,而mkdirs()創建成功了

       情況四:【相比於前兩種情況,將mkdir()和mkdirs()的順序對調】我這裏傳入了一個路徑:E:\\ideaSpace\\readme\\abc,其中abc目錄是不存在的,執行該方法後,mkdir()創建失敗,mkdirs()創建成功

      總結:對於mkdir()和mkdirs()兩個方法來說,如果傳入的路徑有一個以上(>1)節點不存在的時候,需要使用mkdirs()方法才能創建成功,若只有一個(=1)節點不存在的時候,mkdir()和mkdirs()方法都能夠創建成功,若傳入路徑已經完全存在的情況,那不用說,肯定都是不成功的,從源碼裏我們可以看到,因爲在創建之前都有執行   if (exists()) {return false;}   

4.判斷文件或目錄是否存在:public boolean exists():測試傳入的文件或路徑是否已經存在,只有當該文件或路徑已經存在時,返回true,其他任何情況otherwise,都返回false。

/**
     * Tests whether the file or directory denoted by this abstract pathname
     * exists.
     *
     * @return  <code>true</code> if and only if the file or directory denoted
     *          by this abstract pathname exists; <code>false</code> otherwise
     *
     * @throws  SecurityException
     *          If a security manager exists and its <code>{@link
     *          java.lang.SecurityManager#checkRead(java.lang.String)}</code>
     *          method denies read access to the file or directory
     */
    public boolean exists() {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkRead(path);
	}
	return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0);
    }

5.刪除文件或目錄:public boolean delete():該方法根據傳入的文件或參數,用於刪除指定的文件或目錄,需要注意的一點就是:If
   this pathname denotes a directory, then the directory must be empty in order to be deleted:如果傳入的是目錄的情況下,只有當該目錄爲空的時候,才能夠刪除該目錄

/**
     * Deletes the file or directory denoted by this abstract pathname.  If
     * this pathname denotes a directory, then the directory must be empty in
     * order to be deleted.
     *
     * @return  <code>true</code> if and only if the file or directory is
     *          successfully deleted; <code>false</code> otherwise
     *
     * @throws  SecurityException
     *          If a security manager exists and its <code>{@link
     *          java.lang.SecurityManager#checkDelete}</code> method denies
     *          delete access to the file
     */
    public boolean delete() {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkDelete(path);
	}
	return fs.delete(this);
    }

6.判斷是否爲文件:public boolean isFile()         判斷是否爲目錄:public boolean isDirectory()

   獲取文件的名字:public String getName()      獲取文件的大小:public long length()

【以上四個方法是我們在對文件操作時,時常需要用到的方法,但是具體好像沒什麼可講的,唯獨getName()方法,需要注意的時,該方法的返回值只是文件的名字,不包含上一級的目錄】

 public boolean isDirectory() {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkRead(path);
	}
	return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY)
		!= 0);
    }


 public boolean isFile() {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkRead(path);
	}
	return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0);
    }

public String getName() {
	int index = path.lastIndexOf(separatorChar);
	if (index < prefixLength) return path.substring(prefixLength);
	return path.substring(index + 1);
    }

public long length() {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkRead(path);
	}
	return fs.getLength(this);
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章