1.3.4 File 类 File 可以表示文件也可以表示目录,File 类控制所有硬盘操作 b& I: R# b* K
构造器:
8 n& T9 a; ~: e File(File parent,String child) 用父类和文件名构造6 [" y1 Q5 E4 a
File(String pathname) 用绝对路径构造
$ B! b) P6 ]# T2 } File(String parent,String child) 用父目录和文件名构造
. y/ C7 u* ]0 {4 {! _! ? File(URI uri) 用远程文件构造
* ]7 S+ P m. u( Q" i4 d 常用方法:
' q: p0 \- k; n+ \, Z! K: Z boolean createNewFile();8 @ C. r/ M) l" B6 D% I- E& Q2 E k
boolean exists();$ j' u/ M [4 b6 S4 c
例子:9 Z& T: r4 J' Q# \
//建立 test.txt 文件对象,判断是否存在,不存在就创建
1 D7 Q1 ]/ J0 M( v$ w' I. x import java.io.*;( I: R" j, b) ~8 N! o
public class CreateNewFile{ w4 m" O3 d1 Z; W9 g! ]! D( E8 x
public static void main(String args[]){
! R* A5 K( b- g/ \$ O2 Y/ a* E File f=new File("test.txt");% r, e0 t5 J6 c! |& H) d, P
try{
" f0 G. }/ L( ]" R1 j if(!f.exists())
! w: c, s* s2 }2 _; q f.createNewFile();
6 u7 @/ ?: [$ F+ C' z1 e$ P else' f, O8 ~& ?$ \9 T. Y/ x
System.out.println("exists");& w- ]* ?/ B( e! \4 t9 }6 {+ K
}catch(Exception e){
) H' C" m1 d5 ]$ c' N1 \+ v e.printStackTrace();* l+ z9 x9 I' `+ ]& Z9 G0 ?2 v, K3 U0 v
}
$ |1 @' h5 }& X" _$ T% U }% }; V% _( Q+ R! [* L
} g' `# {2 @; A% b5 N) X' n
boolean mkdir()/mkdirs()
' u& b/ P& m8 W2 Z boolean renameTo(File destination)$ `- I% \! c- M& ^$ z8 E" i3 S
例子://看一下这 mkdir()/mkdirs() 的区别和 renameTo 的用法
+ ^; m6 S3 O* V# ? import java.io.*;/ l7 E3 o t5 |: D e
public class CreateDir{
6 B2 j, w" }) _/ Z- l! F public static void main(String args[]){
) x5 e4 t- Z* R h File f=new File("test.txt");
, N' v8 D8 W, q# W File f1=new File("Dir");
4 \" j `6 j8 Q, O File f2=new File("Top/Bottom");- q# o) c! i8 k3 O) {
File f3=new File("newTest.txt");- ?: d) [0 X6 n2 I: E- H- y8 j
try{
: |. B4 y* d) C5 a8 _3 G f.renameTo(f3);& N# F. S, Y+ J: I5 @$ ~& e& h
f1.mkdir();+ }2 M+ n* N& q% T5 D0 B
f2.mkdirs();( X7 f/ k3 l- s, x$ W+ U% I0 u
}catch(Exception e){- o$ J- h- @+ q. f j# ~1 j
e.printStackTrace();
. ]; t9 y- J1 \3 K7 |- _ }( M9 }) y% V, Q5 d6 |/ W
}! l2 c: b# \6 P0 U; c: l6 l* ^0 r
}
- f3 j, |" |3 A, ~ String getPath()/getAbsolutePath()$ L- ?/ p% y& d+ O X4 M; F+ F7 F
String getParent()/getName() |