Java编程中最基础的文件和目录操作方法详解
文件操作
平常经常使用JAVA对文件进行读写等操作,这里汇总一下常用的文件操作。
1、创建文件
publicstaticbooleancreateFile(StringfilePath){ booleanresult=false; Filefile=newFile(filePath); if(!file.exists()){ try{ result=file.createNewFile(); }catch(IOExceptione){ e.printStackTrace(); } } returnresult; }
2、创建文件夹
publicstaticbooleancreateDirectory(Stringdirectory){ booleanresult=false; Filefile=newFile(directory); if(!file.exists()){ result=file.mkdirs(); } returnresult; }
3、删除文件
publicstaticbooleandeleteFile(StringfilePath){ booleanresult=false; Filefile=newFile(filePath); if(file.exists()&&file.isFile()){ result=file.delete(); } returnresult; }
4、删除文件夹
递归删除文件夹下面的子文件和文件夹
publicstaticvoiddeleteDirectory(StringfilePath){ Filefile=newFile(filePath); if(!file.exists()){ return; } if(file.isFile()){ file.delete(); }elseif(file.isDirectory()){ File[]files=file.listFiles(); for(Filemyfile:files){ deleteDirectory(filePath+"/"+myfile.getName()); } file.delete(); } }
5、读文件
(1)以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件
publicstaticStringreadFileByBytes(StringfilePath){ Filefile=newFile(filePath); if(!file.exists()||!file.isFile()){ returnnull; } StringBuffercontent=newStringBuffer(); try{ byte[]temp=newbyte[1024]; FileInputStreamfileInputStream=newFileInputStream(file); while(fileInputStream.read(temp)!=-1){ content.append(newString(temp)); temp=newbyte[1024]; } fileInputStream.close(); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returncontent.toString(); }
(2)以字符为单位读取文件,常用于读文本,数字等类型的文件,支持读取中文
publicstaticStringreadFileByChars(StringfilePath){ Filefile=newFile(filePath); if(!file.exists()||!file.isFile()){ returnnull; } StringBuffercontent=newStringBuffer(); try{ char[]temp=newchar[1024]; FileInputStreamfileInputStream=newFileInputStream(file); InputStreamReaderinputStreamReader=newInputStreamReader(fileInputStream,"GBK"); while(inputStreamReader.read(temp)!=-1){ content.append(newString(temp)); temp=newchar[1024]; } fileInputStream.close(); inputStreamReader.close(); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returncontent.toString(); }
(3)以行为单位读取文件,常用于读面向行的格式化文件
publicstaticList<String>readFileByLines(StringfilePath){ Filefile=newFile(filePath); if(!file.exists()||!file.isFile()){ returnnull; } List<String>content=newArrayList<String>(); try{ FileInputStreamfileInputStream=newFileInputStream(file); InputStreamReaderinputStreamReader=newInputStreamReader(fileInputStream,"GBK"); BufferedReaderreader=newBufferedReader(inputStreamReader); StringlineContent=""; while((lineContent=reader.readLine())!=null){ content.add(lineContent); System.out.println(lineContent); } fileInputStream.close(); inputStreamReader.close(); reader.close(); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returncontent; }
6、写文件
字符串写入文件的几个类中,FileWriter效率最高,BufferedOutputStream次之,FileOutputStream最差。
(1)通过FileOutputStream写入文件
publicstaticvoidwriteFileByFileOutputStream(StringfilePath,Stringcontent)throwsIOException{ Filefile=newFile(filePath); synchronized(file){ FileOutputStreamfos=newFileOutputStream(filePath); fos.write(content.getBytes("GBK")); fos.close(); } }
(2)通过BufferedOutputStream写入文件
publicstaticvoidwriteFileByBufferedOutputStream(StringfilePath,Stringcontent)throwsIOException{ Filefile=newFile(filePath); synchronized(file){ BufferedOutputStreamfos=newBufferedOutputStream(newFileOutputStream(filePath)); fos.write(content.getBytes("GBK")); fos.flush(); fos.close(); } }
(3)通过FileWriter将字符串写入文件
publicstaticvoidwriteFileByFileWriter(StringfilePath,Stringcontent)throwsIOException{ Filefile=newFile(filePath); synchronized(file){ FileWriterfw=newFileWriter(filePath); fw.write(content); fw.close(); } }
目录操作
目录是一个文件可以包含其他文件和目录的列表。你想要在目录中列出可用文件列表,可以通过使用File对象创建目录,获得完整详细的能在File对象中调用的以及有关目录的方法列表。
创建目录
这里有两个有用的文件方法,能够创建目录:
mkdir()方法创建了一个目录,成功返回true,创建失败返回false。失败情况是指文件对象的路径已经存在了,或者无法创建目录,因为整个路径不存在。
mkdirs()方法创建一个目录和它的上级目录。
以下示例创建“/tmp/user/java/bin”目录:
importjava.io.File; publicclassCreateDir{ publicstaticvoidmain(Stringargs[]){ Stringdirname="/tmp/user/java/bin"; Filed=newFile(dirname); //Createdirectorynow. d.mkdirs(); } }
编译并执行以上代码创建“/tmp/user/java/bin”。
提示:Java自动按UNIX和Windows约定来处理路径分隔符。如果在Windows版本的Java中使用正斜杠(/),仍然可以得到正确的路径。
目录列表
如下,你能够用File对象提供的list()方法来列出目录中所有可用的文件和目录
importjava.io.File; publicclassReadDir{ publicstaticvoidmain(String[]args){ Filefile=null; String[]paths; try{ //createnewfileobject file=newFile("/tmp"); //arrayoffilesanddirectory paths=file.list(); //foreachnameinthepatharray for(Stringpath:paths) { //printsfilenameanddirectoryname System.out.println(path); } }catch(Exceptione){ //ifanyerroroccurs e.printStackTrace(); } } }
基于你/tmp目录下可用的目录和文件,将产生以下结果:
test1.txt test2.txt ReadDir.java ReadDir.class