개발일기/Java
File class : 지정된 폴더의 파일 찾기, 없으면 생성하기
민장미
2023. 5. 1. 22:48
주요 메소드:
list( ) 해당 경로의 파일,폴더의 이름만 반환 (String)
listFiles( ) : 해당 경로의 파일,폴더의 이름 반환(File 형 즉 객체)
mkdir( ) : 폴더를 만들어준다.
package file1;
import java.io.File;
//존재하지 않는 경로도 포함해서 객체를 생성해준다 *****
//파일의 존재 유무, 경로의 존재 유무 등 파일 및 경로와 같은 작업을 처리해주는 클래스다
//파일의 내용을 조작하지는 않는다.
public class File_repeat {
public static void main(String[] args) {
String path = "C:\\KOSMO132\\java\\학원필기\\0501\\myFiles";
File f = new File(path);
if(f.exists()) {
String[] strList = f.list(); // 경로에 있는 파일과 폴더를 모두 반환(문자열)
File[] fileList = f.listFiles();
for(String e: strList) {
if(e.contains(".")) {
System.out.print("파일 :"+e+" ");
}else {
System.out.print("폴더 :"+e+" ");
}
}
System.out.println("33333333");
for(File e: fileList ) {
if(e.isDirectory()) {
System.out.println("폴더 "+e.getName());
}else {
System.out.println("파일:"+e.getName());
}
}
}
//if
}
}
package file1;
import java.io.File;
public class File_repeat2 {
public static void showPath(String orifile) {
File f1 = new File(orifile);
File[] list = f1.listFiles();
String[] list2 = f1.list();
for (File e : list) {
if (e.isDirectory()) {
System.out.println("Directory =>" + e.getName());
} else {
System.out.println("file=>" + e.getName());
}
}
}
public static void main(String[] args) {
String oripath = "C:\\\\KOSMO132\\\\java\\\\학원필기\\\\0501\\\\myFiles";
String path = "C:\\\\KOSMO132\\\\java\\\\학원필기\\\\0501\\\\myFiles\\test\\test2"; // 실제로 폴더가 생성됌
File f1 = new File(path);
if (!f1.exists()) {
System.out.println("해당 경로가 존재하지 않습니다. 그래서 만들겠습니다.");
// 하위 경로를 추상경로로 취급해서 만들 수 있다.
f1.mkdir();
showPath(oripath);
} else {
System.out.println("이미 존재하는 경로입니다.");
showPath(oripath);
}
}// main
}