ファイル/ディレクトリを作成および削除する方法一般的に使用されるファイルクラス
1.Booleanが存在する():ファイルまたはディレクトリが存在するかどうかを判断します
2.Boolean CreateNewFile():新しいファイルを作成します
3.boolean delete():ファイルを削除します
4.boolean mkdirs():再帰的にマルチレベルのディレクトリを作成します
5.File getParentFile():前のディレクトリを取得します
1.ファイルを作成/削除します
try {// Dディスクのデモディレクトリに新しいファイルを作成します:test.txtファイル= newファイル( "d://demo//test.txt"); //ファイルが存在する場合、削除、存在しない、if(!file.exists()){//存在しない場合、file.createNewfile()を作成します。 } else {//存在する、file.delete();を削除します。 }} catch(例外e){e.printstacktrace();}•ディレクトリを作成します
try {// dディスクファイルのデモディレクトリに新しいディレクトリ「/a/b/c」を作成します= new file( "d:// demo // a // b // c"); if(!file.getParentFile()。exists()){//優れたディレクトリは存在しません。優れたディレクトリfile.getParentFile()。mkdirs(); } file.mkdirs();} catch(例外e){e.printstacktrace();}ファイル操作
1.String getName():ファイル名を取得します
2.Long Length():ファイルサイズを取得し、バイトユニットを返します
3.File getParentFile():前のディレクトリのファイルオブジェクトを取得します
4.String getParent():前のディレクトリのパスを取得します
5.long lastModified():最後の変更時間
6.boolean isfile():ファイルですか?
[//コンストラクターを使用してファイルを決定してファイルファイル= newファイルを操作します( "d:"+file.separator+"demo"+file.separator+"nokiapptx"); //ファイル名を取得する文字列name = file.getName(); System.out.println( "ファイル名:"+name); //ファイル接尾辞System.out.println( "ファイルサフィックス:"+name.substring(name.lastindexof( "。")+1))を取得します。 //ファイルサイズを取得しますlong length = file.length(); // tyte double size =(double)length/1024; // byte-> kb decimalformat format = new Decimalformat( "0.00"); //上部ディレクトリSystem.out.println(file.getParentFile())を取得します。 System.out.println(file.getParent()); //最後の変更時間を取得long lastModified = file.lastModified(); SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-mm-dd hh:mm:ss");日付date = new Date(lastModified); system.out.println(dateformat.format(date)); //それはfile system.out.println(file.isfile());} catch(例外e){e.printstacktrace();}ですか?ディレクトリ操作
1.String [] list():ディレクトリ内のすべてのファイルの文字列表現を取得します
2.file [] listfiles():ディレクトリ内のすべてのファイルのファイル表現を取得します
3.boolean isdirectory():それはディレクトリですか
try {file file = new file( "d:"+file.separator+"demo"); string [] list = file.list(); for(string s:list){system.out.println(s); } system.out.println( "----------------"); //それはディレクトリSystem.out.println(file.isdirectory())です。 //統計ディレクトリファイルのサブディレクトリとファイルの数[] listfiles = file.listfiles(); int filecount = 0; //ファイル数int directorycount = 0; //ディレクトリ数(ファイルf:listfiles){if(f.isfile()){filecount ++; } else {directoryCount ++; }} system.out.println( "file:"+filecount+"; directory:"+directoryCount+");} catch(Exception e){e.printstacktrace();}再帰出力ディレクトリ
プログラムはそれ自体を呼び出します
//再帰的に出力ディレクトリ情報:ディレクトリサブディレクトリ、ファイルpublic static void print(file file){//それがディレクトリであるかどうかを判断します(file.isdirectory()){//ディレクトリであり、subdirectory and file file [] listfiles = file.listfiles(); if(listfiles!= null){for(file f:listfiles){print(f); }}} system.out.println(file);}要約します
上記は、編集者が紹介したJavaのファイルとディレクトリを作成および削除する方法です。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!