파일/디렉토리 생성 및 삭제 방법 일반적으로 사용되는 파일 클래스
1.boolean이 존재합니다 () : 파일 또는 디렉토리가 존재하는지 확인합니다
2.Boolean createnewfile () : 새 파일을 만듭니다
3.boolean delete () : 파일을 삭제합니다
4.Boolean mkdirs () : 다단계 디렉토리를 재귀 적으로 만듭니다
5. file getParentFile () : 이전 디렉토리를 가져옵니다
1. 파일을 작성/삭제합니다
try {// d disk disk disk : test.txt file = new File ( "d : //demo//test.txt")에서 새 파일을 만듭니다. // 파일이 존재하는 경우, 삭제하고, 존재하지 않으면, if (! file.exists ()) {// 존재하지 않음, file.createnewfile (); } else {// resent, delete file.delete (); }} catch (예외 e) {e.printstacktrace ();}• 디렉토리를 만듭니다
{// d 디스크 파일의 데 디렉토리에서 새 디렉토리 "/a/b/c"를 만듭니다. 파일 파일 = 새 파일 ( "d : // demo // a // b // c"); if (! file.getParentFile (). Exists ()) {// 우수한 디렉토리가 존재하지 않으므로 우수한 디렉토리 파일을 작성하십시오 .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 () : 파일입니까?
{// 생성자를 사용하여 파일을 조작 할 파일을 결정하려면 = 새 파일 ( "d :"+file.separator+"demo"+file.separator+"nokiapptx"); // 파일 이름을 가져옵니다. string name = file.getName (); System.out.println ( "파일 이름 :"+이름); // 파일 접미사 시스템을 가져옵니다. // 파일 크기가 긴 길이 = 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 ()); // 마지막 수정 시간이 길다. 마지막으로 modified = file.lastModified (); simpledateformat dateformat = new simpledateformat ( "yyyy-mm-dd hh : mm : ss"); 날짜 = 새 날짜 (lastModified); System.out.println (dateformat.format (date)); // 파일 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"); 문자열 [] 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 ( "파일 :"+filecount+"; 디렉토리 :"+directoryCount+");} catch (예외 e) {e.printstackTrace ();}재귀 출력 디렉토리
프로그램은 스스로를 호출합니다
// 디렉토리 정보 : 디렉토리 서브 디렉토리, 파일 public static void print (파일 파일) {// 디렉토리가 if (file.isdirectory ())인지 판단합니다. if (listfiles! = null) {for (file f : listfiles) {print (f); }}}} system.out.println (파일);}요약
위는 편집자가 소개 한 Java에서 파일 및 디렉토리를 작성하고 삭제하는 방법입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!