欢迎来到天天文库
浏览记录
ID:6075114
大小:47.00 KB
页数:5页
时间:2018-01-02
《java中file类对文件的几个常见操作实例总结》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、Java中,File类的常用方法2011-10-27byguo今天看了看File相关操作,自己编写了几个常用的方法,现在整理出来,供初学者参考。1文件建立2文件移动3文件拷贝4文件夹拷贝5文件夹遍历文件几个方法经过测试都可用packageguo.IO;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStr
2、eam;importjava.sql.Timestamp;publicclassSomeMethodForFile{/***@paramargs*/publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstub//Filefile=newFile(E:\test\test.txt);//window系统下//Filefile=newFile(E:/test/test.txt);//Linux系统下TestFiletestFile=n
3、ewTestFile();//创建新文件Stringpath="I:\test\1\testfile.txt";//testFile.createFile(path);//修改存放路径及名称,内容也一块复制过去了Stringpath2="I:/test2/2/testfile2.txt";//testFile.refileName(path,path2);//复制一个文件Stringsrc=path;StringtoPath="I:\test3";//testFile.copyFile(src,
4、toPath);//遍历文件夹StringtargetPath="I:\FGOSI";//testFile.searchFile(targetPath);//拷贝一个文件夹testFile.copyDir(targetPath,"I:\FGOSI-bak");}}classTestFile{/**新建一个文件**@parampath*/publicvoidcreateFile(Stringpath){Filefile=newFile(path);if(!file.exists())//判断文件是否存
5、在{try{newFile(file.getParent()).mkdirs();//建立上层文件夹file.createNewFile();//创建文件,执行此语句才产生该文件}catch(IOExceptione){e.printStackTrace();}}else{System.out.println("文件已存在");}//获取文件名Stringfilename=file.getName();//获取文件路径StringfilePath=file.getPath();//获取文件绝对路径Str
6、ingfileAbsolutePath=file.getAbsolutePath();//获取父亲文件路径StringparentPath=file.getParent();//获取父亲文件名StringparentName=newFile(file.getParent()).getName();//获取文件大小longsize=file.length();//获取最后一次修改时间longlastTime=file.lastModified();Stringfilemsg="文件名:"+filename
7、+"路径:"+filePath+"绝对路径:"+fileAbsolutePath+"父文件路径:"+parentPath;filemsg+="文件大小"+size+"最后修改时间:"+newTimestamp(lastTime);System.out.println(filemsg);System.out.println("父亲节点文件夹名称"+parentName);//file.delete();//删除文件}/**修改文件路径及名称,内容也一块移动过去了,相当于“移动”**@p
8、aramfromPath*@paramtoPath*/publicvoidrefileName(StringfromPath,StringtoPath){Filefile1=newFile(fromPath);Filefile2=newFile(toPath);//判断file2路径是否存在,不存在则创建if(!file2.exists()){newFile(file2.getParent()).mkdirs();}file1.rename
此文档下载收益归作者所有