查看完整版本: java中文件操作大全

onions 2007-5-15 09:15

java中文件操作大全

[b]一.获得控制台用户输入的信息[/b]
S8_dH6l4RZ3V [code]
F{DT&H"lo)Tq **获得控制台用户输入的信息+s]\PKq PD
     * @return
!fp'w$Ny:ASO      * @throws IOExceptionNZ,j l4A7y[
     */
,b C ] S [9H+Hx t6S ^ u     public String getInputMessage() throws IOException{
(i3vyr.H9?5P3Swc         System.out.println("请输入您的命令∶"); N oj2F!S8l9M }
        byte buffer[]=new byte[1024];
CyP[[PV4J$p7`         int count=System.in.read(buffer);
~!l5T(h:q         char[] ch=new char[count-2];//最后两位为结束符,删去不要 gM5W0QC$Jn
        for(int i=0;i<count-2;i++)FGC f0B ~;@9c
            ch[i]=(char)buffer[i];!F5p1c3cr!bhw
        String str=new String(ch);
7pom$f Aop(N1g;l$n6C l         return str;
b/vX3Fg\F     }V\Xr6E q1d
[/code]PC&xhn5]{
可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。
3Q j+\|ro !QPFIkw*?
[b]二.复制文件[/b]S`^e(@

Y} \*i cFVE 1.以文件流的方式复制文件
5Yjx G)Sd;p&J [code]
Cd/`2C W]p/O8T"j      /**以文件流的方式复制文件%p$gJ9aU1o+I$p
     * @param src 文件源目录 L(Sb)b+qTi.Cl
     * @param dest 文件目的目录
6Nu(b5d6@!Cb@Y      * @throws IOException  
v k ~IK7Q6\/w      */a1v/a*U-P b/]v5z
    public void copyFile(String src,String dest) throws IOException{
7])D#d*c2W1]d;S9_F;U         FileInputStream in=new FileInputStream(src);
@R I3} X-l/@5Z         File file=new File(dest);9z,Ub2O`V*kx(n_
        if(!file.exists())h5Zdd PRu[2@:P
            file.createNewFile(); H"|`2J,@"P)h"s
        FileOutputStream out=new FileOutputStream(file);/{|"R K5rf
        int c;
&].R7C+z%m!t,]{         byte buffer[]=new byte[1024];
XSr w/oN         while((c=in.read(buffer))!=-1){
4[1[&y8l3E9X5j6h             for(int i=0;i<c;i++)
,F+][Q4Jj9p-s]                 out.write(buffer[i]);         A PtnW` |
        }4Mn"N{5F_!Z
        in.close(); cw\!|2} Y.K+{
        out.close();
;\ mo$lR z'`1~+u`a,C     }(R;UW"|;kv
[/code]kd jEh'~ x
该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式
va:vC,ousI
3Hi%hZd\9alZ \)r [b]三.写文件[/b]a?[4wPs}
1.利用PrintStream写文件%t`H)Ez6zu'p
[code]uCOC {HW
     /**
#J_P'UCk9ID      * 文件输出示例$lY SE/O[
     */4VXS3Nh
    public void PrintStreamDemo(){
0r*y?)c2b%\         try{
({?+b0V4[n s             FileOutputStream out=new FileOutputStream("D:/test.txt");9M @6`,u*O
            PrintStream p=new PrintStream(out);
+~}b1mY#MRL             for(int i=0;i<10;i++)E6s.c$nJb1sd
                p.println("This is "+i+" line");
/Wf)w W2hr         } catch (FileNotFoundException e){__X.P(^-? zU,b;`e
            e.printStackTrace();
5BWK v\d%_         }d(?B3Tt-V;h]Vh
    }^B8lF5ux\{
[/code]%K i3| S5T-Cu4r,S%Y
2.利用StringBuffer写文件k~ F_9a6fwf
[code] `UodP1U
public void StringBufferDemo() throws IOException{h"Q'N.\h0k*t;A
        File file=new File("/root/sms.log");
*\.M/p5Q.[bQD         if(!file.exists())
$o%r.]-T2@"X2Us6s"M             file.createNewFile();d&pL7^a~0\2UW.v$`
        FileOutputStream out=new FileOutputStream(file,true);        
/r9a V:p)Ui'rn         for(int i=0;i<10000;i++){L-l&e%l6P I
            StringBuffer sb=new StringBuffer();*u2t d1R,k
            sb.append("这是第"+i+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 ");
n{"t$g Rr K*Q             out.write(sb.toString().getBytes("utf-8"));'nlt&F}qq8\
        }        ;oYk8?$d6f7L[Hk
        out.close(); Qm S+~*B
    }9S'}%H4UMsZ1PwJ
[/code]1d+K0u%ABA*x
该方法可以设定使用何种编码,有效解决中文问题。
R4L'_+~7n*{D l%L 1w)`X+R iK6W,H
[b]四.文件重命名[/b] E"e `/?'J"yvtco
[code]3V4TB-fg2t
   /**文件重命名x6Y V7C,w^}MXy
     * @param path 文件目录4ZW.`e+b8t/]bH
     * @param oldname  原来的文件名8Sms| l:Q cWV#Q|
     * @param newname 新文件名
z f&D.S @VAUM      */
7c|^`.a1B5M l,q3A     public void renameFile(String path,String oldname,String newname){bpd(H)D(soN``
        if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
'R mF AI             File oldfile=new File(path+"/"+oldname); l+EH6g5J%Q
            File newfile=new File(path+"/"+newname);
U-s6H^/mL/FQ/lF{ @             if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名YIz!i;~@K y
                System.out.println(newname+"已经存在!");l"b&B.GiX
            else{
K"ncs9\WF.a                 oldfile.renameTo(newfile);;DJ+`,to
            }
1].b5OH D5ht-bo$B         }         a{F2l5T Y~
    }
[r5QN,g5\ [/code]iH \_-|"qG
[b]五.转移文件目录[/b]
U MK}7A&R7j1B3h 转移文件目录不等同于复制文件,复制文件是复制后两个目录都存在该文件,而转移文件目录则是转移后,只有新目录中存在该文件。
,j;u ]^Mq$@"l [code]
In {2vY Yn6~      /**转移文件目录y?_OJ |
     * @param filename 文件名 D*| InL!Cm
     * @param oldpath 旧目录!pw*^;FV~2?&Y}C
     * @param newpath 新目录
i H2|4zg _)B&P      * @param cover 若新目录下存在和转移文件具有相同文件名的文件时,是否覆盖新目录下文件,cover=true将会覆盖原文件,否则不操作]9~#~ sr!pl+r
     */
\ Q bsf,y     public void changeDirectory(String filename,String oldpath,String newpath,boolean cover){7{B]-\!Df
        if(!oldpath.equals(newpath)){H0Iz4d GhQ&Vn
            File oldfile=new File(oldpath+"/"+filename);~W8j3op \F
            File newfile=new File(newpath+"/"+filename);-HnrB8SRr
            if(newfile.exists()){//若在待转移目录下,已经存在待转移文件
q+B3P"_y0Gq                 if(cover)//覆盖dO*h]8o`
                    oldfile.renameTo(newfile);
,|P4Z+t"U$u A                 else
6Z I'q Z5} w%h                     System.out.println("在新目录下已经存在:"+filename);
U`Z!X/cE4ZUN             }
N Jae'q iY             else{
NhAm!wz                 oldfile.renameTo(newfile);
*Mli+Ip#k             }
*c `a;V?D+i         }      
#e8tc|I5x+I9m&JT     }:["f*?&x;yARg }
[/code]mzd'jSj1X
[b]六.读文件[/b]
t.q.xL+R%k;]^ z [b]1.利用FileInputStream读取文件[/b]
C&{Ggk4H [b][code]
y*Y7E%ZUSX)v z     /**读文件]3|.{$[r0O*n[G
     * @param path l Z#|%B\
     * @return
h8X:q\{,`6B      * @throws IOException2mO6l#_k7H+r v@f
     */4x5? l/ph[
    public String FileInputStreamDemo(String path) throws IOException{
}+nKQ ea)BFP%E1H         File file=new File(path);.nGT)Y8k8ek1C
        if(!file.exists()||file.isDirectory())
mG(eTu             throw new FileNotFoundException();
!i7kw-gX3`t7Z         FileInputStream fis=new FileInputStream(file);
r2b7i\8U*TE         byte[] buf = new byte[1024];%Rp }f bjgJ
        StringBuffer sb=new StringBuffer();/O4TG8N[]}I ] K
        while((fis.read(buf))!=-1){
n2m6a IV m;s_             sb.append(new String(buf));   
]]$}k ow\             buf=new byte[1024];//重新生成,避免和上次读取的数据重复;b-k[,q*f3x,C
        }
8yTT.mz^ A0oM7Z.O         return sb.toString();/\9r!Q+|U{&o
    } w LwB(X.t+H
[/code][/b]Z^z4h"mM.]4T7N+K
[b]v!BLX U5P
2.利用BufferedReader读取[/b].r y,OZ+P^-D4[
[b]在IO操作,利用BufferedReader和BufferedWriter效率会更高一点 [/b]~ ]3Zc4as paj
[b][code]$\5XCJ!RN(d~
   /**读文件
\E7u9R/J      * @param path,bF!D+]yQ ZBE
     * @return
v~0P4T} Po      * @throws IOException
IN,\ R$B      */2W v2s u7GH
    public String BufferedReaderDemo(String path) throws IOException{
,ks5].c!XN UcK         File file=new File(path);
{;]y2@Lr Ix)kO         if(!file.exists()||file.isDirectory()):lv6w ~ V;^V
            throw new FileNotFoundException();$m-j&X j'^,I-[r
        BufferedReader br=new BufferedReader(new FileReader(file));6O ~7L$Gr3^0O7c6|
        String temp=null;
"N0qVg*R!\o(Z)LN         StringBuffer sb=new StringBuffer();
dm-@0Gr#}`-f/B         temp=br.readLine();aLqS Fg
        while(temp!=null){
Z,I~hrB nm             sb.append(temp+" ");%f4B GN9g }K#l
            temp=br.readLine();
_iSmB9K]         }2oZf.i)ZCV"RI4E
        return sb.toString();
Qs^ zHO     }
K$d$xoh1HO8sC*_ [/code][/b]
ztth0Z X [b]3.利用dom4j读取xml文件[/b]
b:F$p3UJ)V4OJ1t+c [b][code]P8by/W I%{
    /**从目录中读取xml文件 W#S&w!l o9UfJ%a+og
     * @param path 文件目录N~wu:Q2K
     * @return0_\ N!^4LVj
     * @throws DocumentExceptiong)Nmt]0j:c d9[S)n
     * @throws IOException;Np#c#o,s p7P%` SQ
     */+jla8Wrx`
    public Document readXml(String path) throws DocumentException, IOException{
f#PE:}'I o%Js         File file=new File(path);
&q[r e-F |         BufferedReader bufferedreader = new BufferedReader(new FileReader(file));5L:[*Vu;X Q q*X*v4|N
        SAXReader saxreader = new SAXReader();:tBmU.Se EM.u
        Document document = (Document)saxreader.read(bufferedreader);"V*@+o!_'B4F!x&in
        bufferedreader.close();4}+U1XY&s](h*ahp+v
        return document;
/AH.d ^)lDgY-iB     }
7C*}pPc(I0Ra_ [/code][/b]7z.Xi2PC7Fi/f
[b][b]七.创建文件(文件夹)[/b][/b],RS,^:TS L!?&oB
[b]1.创建文件夹 [/b]
'W[c:t)` ? U [b][code]"`CC9x| q jL'D r
/**创建文件夹
fP#r!e2f$uX-e      * @param path  目录2ti6s4zWB#B
     */
4B0|P-g iC[q KJ     public void createDir(String path){
M yxx+^b1Z @         File dir=new File(path);
`$gB N+lT-S         if(!dir.exists())
,d'|s P{ Ig             dir.mkdir();D c6dB^)t8l*y
    }6?5HcjY Pqc
[/code][/b]
htm7Lw3qM;` 2.创建新文件 [b][code]
)L`?t!h-K c /**创建新文件,~3i9u w6D9PgGv
     * @param path 目录
9y+oM$U5Hi7Qi2cm#q6G      * @param filename 文件名3wRAd9W-N
     * @throws IOException
pK&S(Ha5SPj      */,do_DB o e
    public void createFile(String path,String filename) throws IOException{GX@ fW%@}
        File file=new File(path+"/"+filename);`aA/m'Pm
        if(!file.exists())EHz`bw-A9W*}
            file.createNewFile();s+g|)L5o-M*i t
    }7B5C*_b4Qf#Az
[/code][/b]
s5f9hdX,OXEL6p` [b][b]八.删除文件(目录)[/b]
Xu1Q%uj]U(Q%u 1.删除文件 [/b]
'u'l:`"j;h2C9io!o [b][code] E6Th_i j"XN
    /**删除文件tQ@A)H"T$@P},u
     * @param path 目录
l PjA$h#LD      * @param filename 文件名 l:MO f*a w'xn5E%P
     */&U$|KNc3o&s#Z&ceb\
    public void delFile(String path,String filename){}&?7g)j X%Lz f
        File file=new File(path+"/"+filename);7w-FB c~ p7_/c'YR+n
        if(file.exists()&&file.isFile())1r3v~ o4gGaD
            file.delete();
F,ZG(\"y,q!F"i     }
#^[^K `JE [/code][/b]
$LWR+dk&KdI [b]2.删除目录
}I UG2S a-ML p 要利用File类的delete()方法删除目录时,必须保证该目录下没有文件或者子目录,否则删除失败,因此在实际应用中,我们要删除目录,必须利用递归删除该目录下的所有子目录和文件,然后再删除该目录。 [/b]
:P[B#Y4`g _Q)KDA [b][code]
!EJ x*?.uM@-n ~8? /**递归删除文件夹
([m,MCE:G      * @param path+Ob|z.VAaU
     */ nZ![ Y([*x
    public void delDir(String path){ijcWc h
        File dir=new File(path);m%\q*s-t CX
        if(dir.exists()){
Id4G9NGH             File[] tmp=dir.listFiles();
;`K"W%OP?,L             for(int i=0;i<tmp.length;i++){0CF"I\n:toAgF
                if(tmp[i].isDirectory()){?'@+C4D[ i0E&z
                    delDir(path+"/"+tmp[i].getName());0O%I(T1Q2W9O x#d
                }9SbqZ'V
                else{
"aj5??AY6jt                     tmp[i].delete();
#OM YI8A                 }`6i8W#jk"dY2B
            }
s;gb#R&gEH#o             dir.delete();
)v-I0Tic         }b"R%UJ ]-[V
    }
jT kn_ ] [/code]
J(E1FhF#az~ [/b]

2008-4-8 22:12

VfjHUSsPoJa

*** 该帖被屏蔽 ***

hijk968 2008-4-12 08:46

楼上的写得好

*** 作者被禁止或删除 内容自动屏蔽 ***
页: [1]
查看完整版本: java中文件操作大全