-
Java - File클래스언어/JAVA 2023. 7. 24. 12:27
- File은 기본적이면서도 가장 많이 사용되는 입출력 대상이다.
- file클래스는 파일 혹은 디렉토리를 다룰 수 있도록 다양한 메서드를 정의하고 있다.
1. File클래스 생성자
* 파일과 디렉토리는 같은 방법으로 다룬다.
* pathname에는 보통 경로까지 포함새서 지정해줘야하지만, 프로그램이 실행되는 위치와 파일의 위치가 같을 경우
파일명만 사용해도 된다.
File f = new File(//path); File dir = new File(//path); //이미 존재하는 파일을 파일 객체로 참조시 File f = new File(//) //없는 파일을 생성할때 f.createNewFile();
*OutputStream에 경우 해당 스트림을 열고 파일을 쓸 때 파일이 없으면 생성해서 쓴다.
(File을 얻고 추후의 과정일 수 있다.)
* File은 InputStream과 비슷하게 해당 File이 존재해야 한다.
File객체가 있어야 여러 메서드를 활용할 수 있다. 따라서 없으면 만들자
2. File 메서드
2.1 조회와 관련된 메서드
출처: https://www.devkuma.com/docs/java/file-class/ 2.2 조작 수정과 관련된 메서드
출처: https://www.devkuma.com/docs/java/file-class/ 2.3 파일 체크 관련 메서드
출처: https://www.devkuma.com/docs/java/file-class/ 2.4 파일 권한과 관련된 메서드
출처: https://www.devkuma.com/docs/java/file-class/ 2.5 File의 경로와 관련된 멤버변수
static String pathSeparator OS에서 사용하는 경로 구분자 윈도우; 유닉스: static char pathSeparatorChar OS에서 사용하는 경로 구분자 윈도우; 유닉스: static String separator OS에서 사용하는 이름 구분자 윈도우 |, 유닉스/ static String separatorChar OS에서 사용하는 이름 구분자 *파일 조회와 관련된 메서드 중 AbsolutePath()와 CanonicalPath() (정규경로)가 있다.
- 절대경로의 경우 파일시스템 루트를 포함한 파일이 저장된 전체 경로이다.
>이때 현재 디렉토리를 의미하는 .과 같은 기호나 링크를 포함하고 있을 경우
> 절대 경로는 둘 이상일 수도 있다.
- 정규경로는 파일당 존재하는 단 하나의 경로이다.
예제
1. 디렉토리에 있는 파일과 폴더 읽기
public class FileEx1 { public static void main(String[] args){ File f = new File("C:\\apache-tomcat-9.0.71"); if(!f.exists() || !f.isDirectory()){ System.out.println("유효하지않음"); System.exit(0); } File[] files = f.listFiles(); for(File fs : files){ String name = fs.getName(); System.out.println(fs.isDirectory() ? "["+name+"]":name); } } }
예제2 : 디렉토리에 포함된 하위디렉토리 수와 파일 수 출력해줌 + 디렉토리명
public class FileEx2 { static int totalFiles =0; static int totalDirs = 0; public static void main(String[] args){ File f = new File("C:\\apache-tomcat-9.0.71"); if(!f.exists() || !f.isDirectory()){ System.out.println("유효하지않음"); System.exit(0); } printDir(f); System.out.println(totalFiles +" 총 파일 수 "); System.out.println(totalDirs +" 총 디렉 수 "); } private static void printDir(File f) { System.out.println(f.getAbsoluteFile()+"디렉토리"); File[] files = f.listFiles(); ArrayList subdir = new ArrayList(); for(int i=0; i<files.length;i++){ String name = files[i].getName(); if(files[i].isDirectory()){ name = "["+files[i].getName()+"]"; subdir.add(i+""); System.out.println(name); } } int dirNum = subdir.size(); int fileNum = files.length - dirNum; totalDirs = dirNum; totalFiles = fileNum; System.out.println(fileNum +" 개의 파일 " +dirNum +" 개의 디렉토리"); System.out.println(); for(int i=0; i<subdir.size();i++){ int idx = Integer.parseInt((String)subdir.get(i)); printDir(files[idx]); } } }
예제 3: 현재 디렉토리에 속한 파일과 디렉토리의 이름과 크기 상세정보 보기
public class FileEx3 { public static void main(String[] args){ String currdir = System.getProperty("user.dir"); File dir = new File(currdir); File[] files = dir.listFiles(); for(int i=0; i<files.length;i++){ File f =files[i]; String name = f.getName(); SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:mma"); // Date 클래스 포맷용 String attribute=""; String size =""; if(f.isDirectory()){ attribute ="DIR"; }else{ size = f.length()+""; attribute = f.canRead() ? "R":" "; attribute = f.canWrite() ? "W":" "; attribute = f.isHidden() ? "H": " "; } System.out.printf("%s %3s %6s %s\n",df.format(new Date(f.lastModified())),attribute,size,name); } } }
예제 4: 현재 디렉토리,파일 등을 시간,크기,이름 순으로 오름차순, 내림차순 정렬
public class FileEx4 { public static void main(String[] args){ final char option = 't'; String currdir = System.getProperty("user.dir"); File dir = new File(currdir); File[] files = dir.listFiles(); //정렬기준 Comparator comp = new Comparator() { @Override public int compare(Object o1, Object o2) { long time1 = ((File)o1).lastModified(); long time2 = ((File)o2).lastModified(); long length1 = ((File)o1).length(); long length2 = ((File)o2).length(); String name1 = ((File)o1).getName(); String name2 = ((File)o2).getName(); int result =0; switch (option){ case 't' : if(time1 - time2 >0) result = 1; //1이면 뒤가 앞으로 else if (time1 - time2 == 0) result =0; else if (time1 - time2 <0) result = -1; // -1이면 앞이 앞으로 break; case 'T': if(time1 - time2 >0) result = -1; else if (time1 - time2 == 0) result =0; else if (time1 - time2 <0) result = 1; break; case 'l': if(length1 - length2>0) result = 1; else if (length1 - length2 == 0) result =0; else if (length1 - length2 <0) result = -1; break; case 'L': if(length1 - length2>0) result = -1; else if (length1 - length2 == 0) result =0; else if (length1 - length2 <0) result = 1; break; case 'n' : result = name1.compareTo(name2); break; case 'N': result = name2.compareTo(name1); } return result; } @Override public boolean equals(Object o){return false;} //not used }; Arrays.sort(files,comp); for(int i=0; i<files.length;i++){ File f =files[i]; String name = f.getName(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mma"); String attribute=""; String size =""; if(f.isDirectory()){ attribute ="DIR"; }else{ size = f.length()+""; attribute = f.canRead() ? "R":" "; attribute = f.canWrite() ? "W":" "; attribute = f.isHidden() ? "H": " "; } System.out.printf("%s %3s %6s %s\n",df.format(new Date(f.lastModified())),attribute,size,name); } } }
예제 5: 하위 디렉토리까지 모든 폴더에서 특정 글자 찾기
public class FileEx5 { static int found =0; public static void main(String args[]){ String currdir = System.getProperty("user.dir"); String keyword = "exit"; File dir = new File(currdir); if(!dir.exists() || !dir.isDirectory()){ System.out.println("없는 디렉토리"); System.exit(0); } try{ findInFiles(dir,keyword); }catch (IOException e){ e.printStackTrace(); } System.out.println(); System.out.println(found +"개 찾음"); } private static void findInFiles(File dir, String keyword) throws IOException{ File[] files = dir.listFiles(); //showFileList(files); for(int i=0; i<files.length;i++){ if(files[i].isDirectory()) findInFiles(files[i],keyword); //보통 하위폴더가 먼저 온다 else{ String filename = files[i].getName(); String extension = filename.substring(filename.lastIndexOf(".")+1); extension = ","+extension+","; if(",java,txt,bak,".indexOf(extension) == -1)continue; //선택된 파일이 위 확장자 아니라면 continue; filename = dir.getAbsolutePath()+File.separator+filename; FileReader fr = new FileReader(filename);//파일을 읽기 위한 스트림 BufferedReader br = new BufferedReader(fr); String data =""; int lineNum = 0; while((data = br.readLine()) != null){ lineNum++; if(data.indexOf(keyword) != -1){ //한줄씩 읽어서, 줄 안에 원하는 키워드 있으면, 출력 found ++; System.out.println("["+filename+"]"+"("+lineNum+")"+data); } } br.close(); } } } private static void showFileList(File[] files) { for(File f:files){ if(f.isDirectory()){ System.out.println("[dir]"+f.getName()); }else { System.out.println(f.getName()); } } } }
참고자료: 자바의 정석 (남궁성)
이것이 자바다(신용권,임경균)
https://www.devkuma.com/docs/java/file-class/
Java java.io 패키지 File 클래스
File 클래스는 입출력에 필요한 파일 및 디렉토리에 관한 정보를 다를 수 있다. File 클래스는 파일과 디렉토리의 접근 권한, 생성된 시간, 마지막 수정 일자, 크기, 경로 등의 정보를 얻을 수 메소
www.devkuma.com
'언어 > JAVA' 카테고리의 다른 글
Java - 일급컬렉션 (0) 2023.07.25 Servlet-JSP MVC07 파일 수정하기 (0) 2023.07.24 Java - io 직렬화(Serialization) (0) 2023.07.24 nextStep - 자동차 경주 일급 컬렉션 만들기 (0) 2023.07.23 nextStep - 모든 원시값과 문자열 포장 (0) 2023.07.23