java文件操作大全

发表于:2008-4-10 14:35

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:网络转载

四.文件重命名

 

    /**文件重命名
     * 
@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读取文件

 

2.利用BufferedReader读取

在IO操作,利用BufferedReader和BufferedWriter效率会更高一点

 

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;
    }

 

32/3<123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号