【转载自:https://mp.weixin.qq.com/s/KnSUprd6Z7zbpZAVR1OEdw和https://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. 普通类和抽象类有哪些区别?
- 普通类可以使用new关键字来实例化对象,自己的方法自己实现,而抽象类不行,它里面的抽象方法需要通过子类来实现它,因为抽象类需要子类来实现,所以抽象类是不能使用private关键字修饰的
- 普通类中不能有抽象方法,抽象类中既可以有抽象方法,也可以有非抽象方法
- 普通方法可以使用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);
}