首页 > 开发 > Java > 正文

使用技巧:对Java编程中的文件操作详解

2024-07-13 09:55:06
字体:
来源:转载
供稿:网友

一.获得控制台用户输入的信息

/** *//**获得控制台用户输入的信息     * @return     * @throws ioexception     */    public string getinputmessage() throws ioexception...{        system.out.println("请输入您的命令∶");        byte buffer[]=new byte[1024];        int count=system.in.read(buffer);        char[] ch=new char[count-2];//最后两位为结束符,删去不要        for(int i=0;i<count-2;i++)            ch[i]=(char)buffer[i];        string str=new string(ch);        return str;    }

可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。

二.复制文件

1.以文件流的方式复制文件

/** *//**以文件流的方式复制文件     * @param src 文件源目录     * @param dest 文件目的目录     * @throws ioexception       */    public void copyfile(string src,string dest) throws ioexception...{        fileinputstream in=new fileinputstream(src);        file file=new file(dest);        if(!file.exists())            file.createnewfile();        fileoutputstream out=new fileoutputstream(file);        int c;        byte buffer[]=new byte[1024];        while((c=in.read(buffer))!=-1)...{            for(int i=0;i<c;i++)                out.write(buffer[i]);                }        in.close();        out.close();    }

该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式

三.写文件

1.利用printstream写文件

/** *//**     * 文件输出示例     */    public void printstreamdemo()...{        try ...{            fileoutputstream out=new fileoutputstream("d:/test.txt");            printstream p=new printstream(out);            for(int i=0;i<10;i++)                p.println("this is "+i+" line");        } catch (filenotfoundexception e) ...{            e.printstacktrace();        }    }

2.利用stringbuffer写文件

public void stringbufferdemo() throws ioexception......{        file file=new file("/root/sms.log");        if(!file.exists())            file.createnewfile();        fileoutputstream out=new fileoutputstream(file,true);                for(int i=0;i<10000;i++)......{            stringbuffer sb=new stringbuffer();            sb.append("这是第"+i+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 ");            out.write(sb.tostring().getbytes("utf-8"));        }                out.close();    }

该方法可以设定使用何种编码,有效解决中文问题。

四.文件重命名

/** *//**文件重命名     * @param path 文件目录     * @param oldname  原来的文件名     * @param newname 新文件名     */    public void renamefile(string path,string oldname,string newname)...{        if(!oldname.equals(newname))...{//新的文件名和以前文件名不同时,才有必要进行重命名            file oldfile=new file(path+"/"+oldname);            file newfile=new file(path+"/"+newname);            if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名                system.out.println(newname+"已经存在!");            else...{                oldfile.renameto(newfile);            }         }             }

五.转移文件目录

转移文件目录不等同于复制文件,复制文件是复制后两个目录都存在该文件,而转移文件目录则是转移后,只有新目录中存在该文件。

/** *//**转移文件目录     * @param filename 文件名     * @param oldpath 旧目录     * @param newpath 新目录     * @param cover 若新目录下存在和转移文件具有相同文件名的文件时,      是否覆盖新目录下文件,cover=true将会覆盖原文件,否则不操作     */    public void changedirectory(string filename,string oldpath,string newpath,boolean cover)...{        if(!oldpath.equals(newpath))...{            file oldfile=new file(oldpath+"/"+filename);            file newfile=new file(newpath+"/"+filename);            if(newfile.exists())...{//若在待转移目录下,已经存在待转移文件                if(cover)//覆盖                    oldfile.renameto(newfile);                else                    system.out.println("在新目录下已经存在:"+filename);            }            else...{                oldfile.renameto(newfile);            }        }           }

六.读文件

1.利用fileinputstream读取文件

/** *//**读文件     * @param path     * @return     * @throws ioexception     */    public string fileinputstreamdemo(string path) throws ioexception...{        file file=new file(path);        if(!file.exists()||file.isdirectory())            throw new filenotfoundexception();        fileinputstream fis=new fileinputstream(file);        byte[] buf = new byte[1024];        stringbuffer sb=new stringbuffer();        while((fis.read(buf))!=-1)...{            sb.append(new string(buf));                buf=new byte[1024];//重新生成,避免和上次读取的数据重复        }        return sb.tostring();    }

2.利用bufferedreader读取

在io操作,利用bufferedreader和bufferedwriter效率会更高一点

/** *//**读文件     * @param path     * @return     * @throws ioexception     */    public string bufferedreaderdemo(string path) throws ioexception...{        file file=new file(path);        if(!file.exists()||file.isdirectory())            throw new filenotfoundexception();        bufferedreader br=new bufferedreader(new filereader(file));        string temp=null;        stringbuffer sb=new stringbuffer();        temp=br.readline();        while(temp!=null)...{            sb.append(temp+" ");            temp=br.readline();        }        return sb.tostring();    }

3.利用dom4j读取xml文件

/** *//**从目录中读取xml文件     * @param path 文件目录     * @return     * @throws documentexception     * @throws ioexception     */    public document readxml(string path) throws documentexception, ioexception...{        file file=new file(path);        bufferedreader bufferedreader = new bufferedreader(new filereader(file));        saxreader saxreader = new saxreader();        document document = (document)saxreader.read(bufferedreader);        bufferedreader.close();        return document;    }

七.创建文件(文件夹)

1.创建文件夹 /** *//**创建文件夹

* @param path  目录     */    public void createdir(string path)...{        file dir=new file(path);        if(!dir.exists())            dir.mkdir();    }

2.创建新文件 /** *//**创建新文件

* @param path 目录     * @param filename 文件名     * @throws ioexception     */    public void createfile(string path,string filename) throws ioexception...{        file file=new file(path+"/"+filename);        if(!file.exists())            file.createnewfile();    }

八.删除文件(目录)

1.删除文件

/**删除文件     * @param path 目录     * @param filename 文件名     */    public void delfile(string path,string filename)...{        file file=new file(path+"/"+filename);        if(file.exists()&&file.isfile())            file.delete();    }

2.删除目录

要利用file类的delete()方法删除目录时,必须保证该目录下没有文件或者子目录,否则删除失败,因此在实际应用中,我们要删除目录,必须利用递归删除该目录下的所有子目录和文件,然后再删除该目录。

/**递归删除文件夹     * @param path     */    public void deldir(string path)...{        file dir=new file(path);        if(dir.exists())...{            file[] tmp=dir.listfiles();            for(int i=0;i<tmp.length;i++)...{                if(tmp[i].isdirectory())...{                    deldir(path+"/"+tmp[i].getname());                }                else...{                    tmp[i].delete();                }            }            dir.delete();        }    }

商业源码热门下载www.html.org.cn

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表