본문 바로가기
Java | spring/Java Basic

Java class file, 자바 파일 클래스 주요 메소드

by 워니 wony 2019. 5. 8.

파일인지 아닌지 판단하는 메소드

boolean

isDirectory()

Tests whether the file denoted by this abstract pathname is a directory.

boolean

isFile()

Tests whether the file denoted by this abstract pathname is a normal file.

package com.file.exam01;

import java.io.File;

public class FileTest01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//File f = new File("c:/my/hello.txt");
		File f = new File("c:/my");
		boolean r = f.isFile();
		System.out.println(r);
	}
}

(결과값)

false

 

 

 

폴더 내의 파일 목록 출력

String[]

list()

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

package com.file.exam01;

import java.io.File;

public class FileTest01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		File f = new File("c:/my");
		
		String []arr =f.list();
		
		for ( String x : arr)
		{
			System.out.println(x);
		}
	}
}

(결과값)

123

a.jpg

a.pan

com.txt

dkdkd

dsfsdfsd.txt

hello.txt

pic

wiki

wiki.txt

wiki2

 

파일과 폴더 구별 예제

- 해당 폴더에서 리스트가 파일인지 디렉토리인지 확인 하는 방법

Constructor and Description

File(File parent, String child)

Creates a new File instance from a parent abstract pathname and a child pathname string.

File(String pathname)

Creates a new File instance by converting the given pathname string into an abstract pathname.

File(String parent, String child)

Creates a new File instance from a parent pathname string and a child pathname string.

package com.file.exam01;

import java.io.File;

public class FileTest01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		File file = new File("c:/windows");
		
		String []arr =file.list();
		
		for ( String x : arr)
		{
			//File f = new File("c:/windows/", x);
			File f = new File(file, x);

			String re ="";
			if (f.isFile()){
				re = "파일";
			}
			else{
				re = "디렉토리";
			}
			System.out.println(x+" : "+re);
		}
	}
}

(결과값)

addins : 디렉토리

AppCompat : 디렉토리

AppPatch : 디렉토리

assembly : 디렉토리

bfsvc.exe : 파일

Boot : 디렉토리

bootstat.dat : 파일

Branding : 디렉토리

CSC : 디렉토리

Csup.txt : 파일

 

 

메소드로 파일 지우기

boolean

delete()

Deletes the file or directory denoted by this abstract pathname.

package com.file.exam01;

import java.io.File;

public class FileTest01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		File file = new File("C:/my/dsfsdfsd.txt");
		
		file.delete();
	}
}

(결과값)

파일이 삭제됨 / 휴지통으로 옮겨진다.

반응형

댓글