Недавно, чтобы изменить названия файлов большого количества любимых американских драм, я написал виджет, используя Swing. Код является частью обработки файлов. Конкретный контент заключается в следующем
пакет date.steuern; Импорт java.io.bufferedReader; импорт java.io.file; import java.io.fileinputstream; импорт java.io.filenotfoundexception; импорт java.io.fileoutputstream; import java.io.filewriter; импорт java.io.ioexcept java.io.randomaccessfile; import java.nio.bytebuffer; импорт java.nio.channels.fileChannel; import java.util.arraylist; импорт java.util.arrays; import java.util.collections; импорт java.util.list; import java.util.laging.Lelections; импорт java.util.list; import java.util.laging. java.util.logging.logger; /** * * @author s.watson */public class fileTools {public fileTools () {}/** * FormatPath Escape Directory * * @param Path * @return */public Static Formatpath (String Path) {return Path.replaceall ("////", "/"); } / ** * CombinePath Pail Merge * * @param eins * @param zwei * @return * / private Static String CombinePath (String eins, String zwei) {String dori = ""; eins = null == eins? ": Formatpath (EINS); zwei = null == zwei? "": Formatpath (Zwei); if (! eins.endswith ("/") && zwei.indexof ("/")! = 0) {dori = eins + "/" + zwei; } else {dori = (eins + zwei) .replaceall ("//", "/"); } вернуть Дори; } / ** * List2Array списка массив конвертации * * @param list * @return * / private static string [] list2array (list list) {string array [] = (string []) list.toarray (new String.size.size ()]); вернуть массив; } / ** * cp -копия файла * * @param source * @param destination * @param lo try {file srcfile = new File (source); File desfile = new File (destination); list.addall (cp (srcfile, desfile, loop)); } catch (Exception ex) {j2log (null, null, ex); } return List; } / ** * cp -копия файла * * @param source * @param destination * @param lo try {if (! source.exists () || source.isdirectory ()) {бросить новый filenotfoundexception (); } list.add (cp (source, destination)); if (loop) {string [] subfile = source.list (); for (string subpath: subfile) {string src = combinePath (source.getPath (), subpath); // исходный путь файла subfile string des = combinepath (destination.getPath (), subpath); // Целевой путь субфил -файла subfile = new File (src); if (subfile.ishile ()) {list.add (cp (src, des)); } else if (subfile.isdirectory () && loop) {list.addall (cp (src, des, loop)); }}}}} catch (Exception ex) {j2log (null, null, ex); } return List; } / ** * CP Одно файл копировать файл * * @param source * @param destination * @return * / public static file cp (String Source, String design) {file desfile = null; try {file srcfile = new File (source); desfile = новый файл (назначение); desfile = cp (srcfile, desfile); } catch (Exception ex) {j2log (null, null, ex); } return desfile; } / ** * cp Один файл копировать файл * * @param source * @param destination * @return * / public static file cp (источник файла, файл назначения) {fileInputStream in = null; FileOutputStream OUT = null; FileChannel Inc = null; FileChannel outc = null; try {if (! source.exists () || source.isdirectory ()) {бросить новый filenotfoundexception (); } if (source.getPath (). equals (destination.getPath ())) {return Source; } long allbytes = du (источник, false); if (! destination.exists ()) {destination.createnewfile (); } in = new FileInputStream (source.getPath ()); out = new FileOutputStream (назначение); inc = in.getChannel (); outc = out.getChannel (); Bytebuffer bytebuffer = null; Длина длина = 2097152; // Основной размер, по умолчанию длиной 2 м _2M = 2097152; while (inc.position () <inc.size ()) {if (allbytes> (64 * length)) {// Если размер файла превышает 128 м, кэш изменяется на 64M длины = 32 * _2m; } else if (allbytes> (32 * length)) {// Если размер файла превышает 64 м, кэш изменяется на длину 32 м = 16 * _2m; } else if (allbytes> (16 * length)) {// Если размер файла больше 32 м, кэш изменяется на 16M длины = 8 * _2m; } else if (allbytes> (8 * length)) {// Если размер файла больше 16м, кэш изменяется на 8m длины = 4 * _2m; } else if (allbytes> (4 * length)) {// Если размер файла больше 8 м, кэш изменяется на 4M длины = 2 * _2m; } else if (allbytes> (2 * length)) {// Если размер файла больше 4м, кэш изменяется на 2M длины = _2m; } else if (allbytes> (length)) {// Если размер файла больше 2m, кэш изменяется на 1M длины = _2m/2; } else if (allbytes <length) {// Если файл меньше базового размера, выходной длины напрямую = allbytes; } allbytes = inc.size () - inc.position (); bytebuffer = bytebuffer.allocatedirect ((int) длина); Inc. Reading (bytebuffer); bytebuffer.flip (); outc.write (bytebuffer); Outc.force (false); }} catch (Exception ex) {j2log (null, null, ex); } наконец {try {if (null! = inc) {inc.close (); } if (null! = outc) {outc.close (); } if (null! = in) {in.close (); } if (null! = out) {out.close (); }} catch (Exception ex) {j2log (null, null, ex); }} возврат назначения; } / ** * Переименование файла reName * * @param filepath * @param от * @param to * @return * / public static file rename (string filepath, string from, string to) {file newfile = null; try {file oldfile = new File (combainpath (filePath, от)); newFile = новый файл (combainPath (filePath, to)); переименовать (newfile, oldfile); } catch (Exception ex) {j2log (null, null, ex); } вернуть newfile; } / ** * Переименование файла reName * * @param to * @param from * @return * / public static file rename (файл из, файл в) {try {string newpath = to.getpath (); String oldpath = from.getPath (); if (! oldpath.equals (newpath)) {if (! to.exists ()) {from.renameto (to); }}} catch (Exception ex) {j2log (null, null, ex); } вернуться в; } / ** * MV MOVE FILE * * @param Filename * @param Source * @param назначение * @param Cover * / public static void mv (string fileename, источник строки, строка назначения, логическое покрытие) {try {if (! source.equals (destination)) {file letfile = new File (combainpath (source, filename)); File newfile = new File (combainpath (destination, filename)); MV (OldFile, NewFile, Cover); }} catch (Exception ex) {j2log (null, null, ex); }} / ** * MV MOVE File * * @param Source * @param назначение * @param Cover * / public static void MV (String Source, String Destination, Boolean Cover) {try {if (! source.equals (destination)) {file oldfile = new File (source); File newfile = new File (destination); MV (OldFile, NewFile, Cover); }} catch (Exception ex) {j2log (null, null, ex); }} / ** * MV MOVE File * * @param Source * @param назначение * @param Cover * / public static void mv (источник файла, пункт назначения файла, логическое покрытие) {try {if (! source.exists ()) {throw new filenotfoundexception (); } StringBuilder filename = new StringBuilder (source.getName ()); if (! Cover && source.getPath (). Equals (destination.getPath ())) {if (filename.indexof (".")> 0) {filename.insert (filename.lastIndexof ("."), "_copy"); } else {filename.append ("_ Copy"); } cp (источник, новый файл (combainpath (source.getParent (), filename.toString ())))); } else {source.renameto (destination); }} catch (Exception ex) {j2log (null, null, ex); }} / ** * Расширения получают информацию о расширении файла * * @param filepath * @param filename * @return * / private static String [] extensions (String filePath, String filename) {string [] extension = {}; try {string fullPath = combinePath (filePath, имя файла); File file = new File (fullPath); расширения (файл); } catch (Exception ex) {j2log (null, null, ex); } return Extension; } / ** * Удлинитель Получает информацию о расширении файла * * @param fullpath * @return * / private static String [] extensions (string fullpath) {string [] extension = {}; try {file file = new File (fullPath); расширения (файл); } catch (Exception ex) {j2log (null, null, ex); } return Extension; } / ** * Удлинитель Получает информацию о расширении файла * * @param file * @return * / private static String [] extensions (файл файла) {string [] extension = {}; try {if (file.ishile ()) {string filename = file.getName (); if (filename.lastindexof (".")> = 0) {int astindex = filename.lastindexof ("."); endension [0] = string.valueof (astindex); // индекс "." Extension [1] = filename.substring (LastIndex + 1); // Расширение расширения [2] = filename.substring (0, antindex); // имя файла}}} catch (Exception ex) {j2log (null, null, ex); } return Extension; } / ** * LS Traversing File * * @param filePath * @param loop * @return * / public Static List <file> ls (String filePath, Boolean Lo try {file file = new File (filePath); list.addall (ls (file, loop)); } catch (Exception ex) {j2log (null, null, ex); } return List; } / ** * LS Traversing file * * @param file * @param lo try {list.add (file); if (! file.isdirectory ()) {list.add (file); } else if (file.isdirectory ()) {file [] sublist = file.listfiles (); Sublist = Filessort (Sublist, True); for (file subfile: sublist) {if (subfile.isdirectory () && loop) {list.addall (ls (subfile.getPath (), loop)); } else {list.add (subfile); }}}} catch (Exception ex) {j2log (null, null, ex); } return List; } / ** * FileSpeort File Sort (по умолчанию порядок восхождения) * * @param parentPath * @param sooblist * @return * / private static file [] fileSsort (file [] infiles, boolean asc) {list <string> files = new ArrayList (); Список <string> dirs = new ArrayList (); for (file subfile: infile) {if (subfile.isdirectory ()) {dirs.add (subfile.getPath ()); } else if (subfile.ishile ()) {files.add (subfile.getPath ()); }} String [] fileArray = {}; if (files.size ()> 0) {fileArray = list2array (files); Arrays.sort (FileArray); if (! asc) {arrays.sort (filearray, collections.reversorder ()); }} String [] dirarray = {}; if (dirs.size ()> 0) {dirarray = list2array (dirs); Arrays.sort (Dirarray); if (! asc) {arrays.sort (dirarray, collections.reversorder ()); }} вернуть concat2fileArray (fileArray, dirarray); } / ** * concat2fileArray Merge Array * * * @param old1 * @param old2 * @return * / private static file [] concat2filearray (string [] old1, string [] old2) {file [] newarray = new file [old1.length + oldength]; for (int i = 0, n = old1.length; i <n; i ++) {newarray [i] = новый файл (Old1 [i]); } for (int i = 0, j = old1.length, n = (old1.length+old2.length); j <n; i ++, j ++) {newarray [j] = новый файл (Old2 [i]); } вернуть newarray; } / ** * Читать текстовый файл чтения * * @param filePath * @param filename * @param charset * @return * / public static stringBuilder Read (String filePath, String FileName, String charset) {StringBuilder sb = new StringBuilder (); try {String fullPath = CombinePath (filePath, имя файла); File file = new File (fullPath); SB.Append (fileTools.tail (file, false, 0, charset)); } catch (Exception ex) {j2log (null, null, ex); } вернуть SB; } / ** * Читать текстовый файл чтения * * @param fullpath * @param charset * @return * / public static stringBuilder Read (String fullPath, String charset) {StringBuilder sb = new StringBuilder (); try {file file = new File (fullPath); SB.Append (fileTools.tail (file, false, 0, charset)); } catch (Exception ex) {j2log (null, null, ex); } вернуть SB; } / ** * Читать текстовый файл чтения * * @param file * @param charset * @return * / public static stringbuilder Read (файл файла, string charset) {stringBuilder sb = new StringBuilder (); try {sb.append (filetools.tail (file, false, 0, charset)); } catch (Exception ex) {j2log (null, null, ex); } вернуть SB; } / ** * Найдите чтение указанной строки текстового файла * * @param filepath * @param filename * @param line * @param charset * @return * / public static stringbuilder find (string filepath, string filename, int line, string charset) {StringBuilder sb = new StringBuilder (); try {String fullPath = CombinePath (filePath, имя файла); File file = new File (fullPath); sb.append (fileTools.tail (file, true, line, charset)); } catch (Exception ex) {j2log (null, null, ex); } вернуть SB; } / ** * Найти Читать указанную строку текстового файла * * @param fullpath * @param line * @param charset * @return * / public static stringbuilder find (string fullpath, int line, string charset) {stringBuilder sb = new StringBuilder (); try {file file = new File (fullPath); sb.append (fileTools.tail (file, true, line, charset)); } catch (Exception ex) {j2log (null, null, ex); } вернуть SB; } / ** * Найти Читать указанную строку текстового файла * * @param file * @param line * @param charset * @return * / public static stringbuilder find (файл файл, int line, string charset) {stringBuilder sb = new StringBuilder (); try {sb.append (filetools.tail (файл, true, line, charset)); } catch (Exception ex) {j2log (null, null, ex); } вернуть SB; } / ** * Хвост Читать текстовый файл * * @param filepath * @param filename * @param charset * @param find * @param line * @return * / public Staticbuilder Tail (String filePath, String Filename, Boolean Find, int line, string charset) {StringBuilder sb = new StringBuilder (); try {String fullPath = CombinePath (filePath, имя файла); File file = new File (fullPath); SB.Append (fileTools.tail (файл, поиск, строка, charset)); } catch (Exception ex) {j2log (null, null, ex); } вернуть SB; } / ** * Хвостое чтение текстового файла * * @param fullpath * @param charset * @param find * @param line * @return * / public static stringbuilder tail (строка FullPath, Boolean Find, int line, string charset) {StringBuilder sb = new StringBuilder (); try {file file = new File (fullPath); SB.Append (fileTools.tail (файл, поиск, строка, charset)); } catch (Exception ex) {j2log (null, null, ex); } вернуть SB; } / ** * Текстовый файл с чтением хвоста * * @param file * @param charset * @param find * @param line * @return * / public static stringbuilder tail (файл файла, логический поиск, int line, string charset) {stringbuilder sb = new StringBuilder (); BufferedReader BufferReader = null; if (null == charset || "" .equals (charset)) {charset = "utf-8"; } try {if (! file.exists () || file.isdirectory ()) {бросить новый filenotfoundexception (); } String fullPath = file.getPath (); BufferReader = new BufferedReader (New InputStreamReader (New FileInputStream (FullPath), charset)); Строка температура; for (int i = 0; (temp = bufferReader.readline ())! = null; i ++) {if (! Найти || line == i) {sb.append (temp); }}} catch (Exception ex) {j2log (null, null, ex); } наконец {if (null! = bufferReader) {try {bufferReader.close (); } catch (ioException ex) {j2log (null, null, ex); }}} вернуть Sb; } / ** * SED прочитать текстовый файл * * @param filepath * @param filename * @param charset * @return * / public Static List <string> sed (String filePath, String filename, String charset) {list> list = new ArrayList (); try {String fullPath = CombinePath (filePath, имя файла); File file = new File (fullPath); list.addall (filetools.sed (file, charset)); } catch (Exception ex) {j2log (null, null, ex); } return List; } / ** * SED Read Text File * * @param fullpath * @param charset * @return * / public Static <string> sed (String fullPath, String charset) {list <string> list = new ArrayList (); try {file file = new File (fullPath); list.addall (filetools.sed (file, charset)); } catch (Exception ex) {j2log (null, null, ex); } return List; } / ** * SED Read Text File * * @param file * @param charset * @return * / public static <string> sed (файл файла, string charset) {list <string> list = new ArrayList (); BufferedReader BufferReader = null; if (null == charset || "" .equals (charset)) {charset = "utf-8"; } try {if (! file.exists () || file.isdirectory ()) {бросить новый filenotfoundexception (); } String fullPath = file.getPath (); BufferReader = new BufferedReader (New InputStreamReader (New FileInputStream (FullPath), charset)); Строка температура; for (int i = 0; (temp = bufferReader.readline ())! = null; i ++) {list.add (temp); }} catch (Exception ex) {j2log (null, null, ex); } наконец {if (null! = bufferReader) {try {bufferReader.close (); } catch (ioException ex) {j2log (null, null, ex); }}} return List; } / ** * Cat Read Text File * * @param filePath * @param filename * @return * / public static byte [] cat (string filepath, string filename) {byte [] output = {}; try {String fullPath = CombinePath (filePath, имя файла); File file = new File (fullPath); output = fileTools.cat (file); } catch (Exception ex) {j2log (null, null, ex); } return output; } / ** * CAT Read Text File * * @param fullpath * @return * / public static byte [] cat (string fullpath) {byte [] output = {}; try {file file = new File (fullPath); output = fileTools.cat (file); } catch (Exception ex) {j2log (null, null, ex); } return output; } / ** * CAT Read Text File * * @param file * @return * / public Static Byte [] cat (файл файла) {inputstream in = null; byte [] output = {}; try {if (! file.exists () || file.isdirectory ()) {бросить новый filenotfoundexception (); } String fullPath = file.getPath (); длинная длина = du (файл, false); Long _2m = 2097152; байт [] байты = новый байт [(int) длину]; in = new FileInputStream (FullPath); for (int count = 0; count! = -1;) {if (длина> 16 * _2m) {length = 4 * _2m; } else if (длина> 8 * _2m) {length = 2 * _2m; } else if (длина> 4 * _2m) {length = _2m; } else if (длина> 2 * _2m) {length = _2m / 2; } else if (длина> _2m) {length = _2m / 4; } else {длина = 4096; } bytes = new Byte [(int) Length]; count = in.read (байты); output = concatArray (байты, выход); длина = in.vailable (); }} catch (Exception ex) {j2log (null, null, ex); } наконец {if (null! = in) {try {in.close (); } catch (Exception ex) {j2log (null, null, ex); }}} вернуть выход; } / ** * Merge Array * * @param old1 * @param old2 * @return * / private static byte [] concatarray (byte [] old1, byte [] old2) {byte [] newarray = new byte [old1.length + old2.length]; System.ArrayCopy (Old1, 0, Newarray, 0, Old1.length); System.ArrayCopy (Old2, 0, Newarray, Old1.length, Old2.length); вернуть Ньюаррея; } / ** * dd файл записи содержимого содержимого содержимого witch * * @param filePath * @param filename * @param * @param isappend * / public static void dd (строка filePath, String fileName, Byte [] Content, Boolean Isappend) {try {String fullPath = CombinePath (filePath, filename); File file = new File (fullPath); Filetools.dd (файл, контент, isappend); } catch (Exception ex) {j2log (null, null, ex); }} / ** * DD записать файл записи содержимое содержимого полного топа * * @param fullpath * @param content * @param isappend * / public static void dd (строка FullPath, Byte [] Content, Boolean isappend) {try {file file = new File (fullPath); Filetools.dd (файл, контент, isappend); } catch (Exception ex) {j2log (null, null, ex); }} / ** * dd записать файл write fullPath Content Content * * @param file * @param content * @param isappend * / public static void dd (файл файла, byte [] content, boolean isappend) {fileOutputStream fileOutputStream = null; try {if (! file.exists ()) {file.createnewfile (); } fileOutputStream = new FileOutputStream (file, isAppend); fileOutputStream.Write (Content); } catch (Exception ex) {j2log (null, null, ex); } наконец {try {if (null! = fileOutputStream) {fileOutputStream.close (); }} catch (ioException ex) {j2log (null, null, ex); }}}} / ** * Содержимое файла записи записи для файла fullPath * * @param filePath * @param filename * @param content * / public static void write (string filepath, string filename, содержимое строки) {try {string fullPath = combinePath (filePath, fileName); File file = new File (fullPath); FileTools.Write (файл, контент, true); } catch (Exception ex) {j2log (null, null, ex); }} / ** * Содержимое записи файла записи для файла fullPath * * @param fullpath * @param content * / public static void write (строка FullPath, String Content) {try {file file = new File (fullPath); FileTools.Write (файл, контент, true); } catch (Exception ex) {j2log (null, null, ex); }} / ** * Содержимое записи файла записи для файла fullPath * * @param file * @param content * / public static void write (файл файла, строка содержимого) {try {filetools.write (file, content, true); } catch (Exception ex) {j2log (null, null, ex); }} / ** * write write (Приложение) Содержание файла для файла FullPath * * @param filePath * @param filename * @param content * @param isappend * / public static void write (строка filepath, string filename, строковое содержимое, логическое isappend) {try {string fullpath = combinepath (filePath, filename); File file = new File (fullPath); Filetools.write (файл, контент, isappend); } catch (Exception ex) {j2log (null, null, ex); }} / ** * write write (Приложение) Содержание файла для файла fullpath * * @param fullpath * @param content * @param isappend * / public static void write (строка FullPath, строка содержимого, логическое isAppend) {try {file file = new File (fullPath); Filetools.write (файл, контент, isappend); } catch (Exception ex) {j2log (null, null, ex); }} / ** * write write (append) Содержание файла для файла fullpath * * @param file * @param content * @param isappend * / public static void write (файл файл, строка содержимого, boolean isappend) {filewriter filewriter = null; try {if (! file.exists ()) {file.createnewfile (); } fileWriter = new FileWriter (file.getPath (), isAppend); filewriter.write (content); } catch (Exception ex) {j2log (null, null, ex); } наконец {if (null! = fileWriter) {try {fileWriter.Close (); } catch (ioException ex) {j2log (null, null, ex); }}}}} / ** * Хвост добавить содержимое содержимого файла в местоположение индекса файла * * @param filePath * @param filename * @param content * @param index * / public static void hail (строка filepath, string fileename, строковое содержимое, длинное индекс) {try {String fullPath = combinePath (filePath, fiLename); File file = new File (fullPath); Filetools.tail (файл, контент, индекс); } catch (Exception ex) {j2log (null, null, ex); }} / ** * Хвост Добавить содержимое содержимого файла в местоположение индекса файла * * @param fullpath * @param content * @param index * / public static void tail (строка FullPath, строка содержимого, Long Index) {try {file file = new File (fullPath); Filetools.tail (файл, контент, индекс); } catch (Exception ex) {j2log (null, null, ex); }} / ** * Хвост Добавить содержимое содержимого файла в местоположение индекса файла * * @param file * @param content * @param index * / public static void tail (файл файл, содержимое строки, длинный индекс) {randomaccessfile randomaccessfile = null; try {if (! file.exists ()) {file.createnewfile (); } randomAccessfile = new randomAccessfile (file.getPath (), "rw"); randomaccessfile.seek (index); randomaccessfile.writebytes (content); } catch (Exception ex) {j2log (null, null, ex); } наконец {if (null! = randomAccessfile) {try {randomAccessfile.close (); } catch (Exception ex) {j2log (null, null, ex); }}}}} / ** * Mkdir Create Directory * * @param filePath * @param filename * @return * / public static file mkdir (string filepath, string filename) {file file = null; try {String fullPath = CombinePath (filePath, имя файла); file = new File (fullPath); file = mkdir (file); } catch (Exception ex) {j2log (null, null, ex); } return file; } / ** * mkdir Create Directory * * @param fullPath * @return * / public Static File Mkdir (String fullPath) {file file = null; try {file = new File (fullPath); file = mkdir (file); } catch (Exception ex) {j2log (null, null, ex); } return file; }/** * mkdir Create Directory * * @param file * @return */public static file mkdir (файл файла) {try {if (! file.exists ()) {file.mkdir (); // create, если папка не существует}} catch (Exception ex) {j2log (null, null, ex); } return file; } / ** * Touch Create File * * @param filePath * @param filename * / public static void touch (String filePath, String filename) {try {String fullPath = CombinePath (filePath, Filename); File file = new File (fullPath); touch (файл); } catch (Exception ex) {j2log (null, null, ex); }} / ** * touch create file * * @param fullpath * / public static void touch (строка FullPath) {try {file file = new File (fullPath); touch (файл); } catch (Exception ex) {j2log (null, null, ex); }}/** * touch create file * * @param file */public static void touch (файл файл) {try {if (! file.exists ()) {file.createnewfile (); // Создать, если файл не существует}} catch (exception ex) {j2log (null, null, ex); }} / ** * rm Удалить файл * * @param filepath * @param filename * / public static void rm (строка filepath, string filename) {try {String fullPath = combinePath (filePath, filename); File file = new File (fullPath); rm (файл); } catch (Exception ex) {j2log (null, null, ex); }} / ** * rm delete file * * @param fullpath * / public static void rm (string fullpath) {try {file file = new File (fullPath); rm (файл); } catch (Exception ex) {j2log (null, null, ex); }} / ** * rm delete file * * @param file * / public static void rm (файл файла) {try {if (! file.exists ()) {бросить новый filenotfoundexception (); } if (file.ishile ()) {file.delete (); }} catch (Exception ex) {j2log (null, null, ex); }} / ** * rmdir Delete Directory * * @param filePath * @param filename * @param goop * / public static void rmdir (строка FilePath, String Filename, Boolean Loop) {try {string fullPath = combinePath (filePath, fileName); Файл dir = new File (fullPath); rmdir (dir, loop); } catch (Exception ex) {j2log (null, null, ex); }} / ** * rmdir Delete Directory * * @param fullPath * @param lo rmdir (dir, loop); } catch (Exception ex) {j2log (null, null, ex); }} / ** * rmdir delete Directory * * @param dir * @param loop * / public static void rmdir (файл dir, boolean goop) {try {if (! dir.exists ()) {throw new filenotfoundexception (); } if (dir.isdirectory ()) {file [] files = dir.listfiles (); int length = files.length; for (int i = 0; i <length && loop; i ++) {if (files [i] .isdirectory ()) {rmdir (files [i], loop); } else {rm (files [i]); }} if (loop || length == 0) {dir.delete (); }}} catch (Exception ex) {j2log (null, null, ex); }} / ** * du Получить фактический размер файла * * @param filepath * @param filename * @param lo try {String fullPath = CombinePath (filePath, имя файла); File file = new File (fullPath); size = du (файл, петля); } catch (Exception ex) {j2log (null, null, ex); } return Size; } / ** * du Получить фактический размер файла * * @param filepath * @param filename * @return * / public static long du (String filePath, String filename) {long size = 0; try {String fullPath = CombinePath (filePath, имя файла); File file = new File (fullPath); size = du (файл, false); } catch (Exception ex) {j2log (null, null, ex); } return Size; } / ** * du Получить фактический размер файла * * @param fullpath * @return * / public static long du (String fullpath) {long size = 0; try {file file = new File (fullPath); size = du (файл, false); } catch (Exception ex) {j2log (null, null, ex); } return Size; } / ** * du Получить фактический размер файла * * @param file * @return * / public static long du (файл файла) {long size = 0; try {size = du (file, false); } catch (Exception ex) {j2log (null, null, ex); } return Size; } / ** * du Получить фактический размер файла * * @param fullpath * @param loop * @return * / public static long du (строка FullPath, Boolean Loop) {Long Size = 0; try {file file = new File (fullPath); size = du (файл, петля); } catch (Exception ex) {j2log (null, null, ex); } return Size; } / ** * du Получить фактический размер файла * * @param file * @param lo длинный размер = 0; попробуйте {if (! file.exists ()) {добавить новый filenotfoundexception (); } if (file.ishile ()) {fileInputStream fis = new FileInputStream (file); fileChannel = fis.getChannel (); size = fileChannel.size (); } else if (file.isdirectory ()) {file [] files = file.listfiles (); int length = files.length; for (int i = 0; i <length && loop; i ++) {if (files [i] .isdirectory ()) {du (файлы [i], loop); } else {size += du (файлы [i], false); }}}} catch (Exception ex) {j2log (null, null, ex); } наконец {if (null! = fileChannel) {try {fileChannel.close (); } catch (Exception ex) {j2log (null, null, ex); }}} return size; }}Выше приведено в этой статье, я надеюсь, что это будет полезно для каждого обучения.