> Java > java지도 시간 > 본문

자바 디렉토리

PHPz
풀어 주다: 2024-08-30 16:02:00
원래의
320명이 탐색했습니다.

Java에서는 파일과 기타 디렉토리를 포함하는 파일 시스템 구조를 디렉토리라고 하며, 이는 다른 유형의 파일과 함께 java.nio.file.files 클래스의 정적 메소드에 의해 작동되며 새로운 디렉토리가 생성됩니다. java에서 Files.CreateDirectories를 사용하여 상위 디렉토리가 없는 경우 상위 디렉토리를 생성하고 새로 생성된 디렉토리에 권한을 설정하기 위해 PossixFilePermissions가 사용됩니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java 디렉토리 생성

디렉토리는 세 가지 방법을 사용하여 생성할 수 있습니다. 그들은:

  • 파일.CreateDirectory
  • 파일.CreateDirectories
  • PosixFilePermissions

Files.CreateDirectory 사용

Files.CreateDirectory() 메서드를 사용하여 새 디렉토리를 생성할 수 있습니다. 파일이 이미 존재함 이미 존재하는 파일이 있는 경우 예외가 발생합니다.

Files.CreateDirectory()를 사용하여 디렉토리 생성을 보여주는 Java의 예제 프로그램

코드:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateDir {
public static void main(String[] args) throws IOException {
String Name = "C:\Users\admin\Desktop\newdir";
Path path1 = Paths.get(Name);
if (!Files.exists(path1)) {
Files.createDirectory(path1);
System.out.println("Creation of directory successful");
} else {
System.out.println("A directory with this name already exists");
}
}
}
로그인 후 복사

출력:

자바 디렉토리

Files.CreateDirectories 사용

이 메소드를 사용하여 새 디렉토리를 생성할 수 있습니다. Files.CreateDirectories는 상위 디렉토리가 생성되지 않은 경우 상위 디렉토리도 생성하며, 디렉토리가 이미 존재하는 경우 이 메소드에서 예외가 발생하지 않습니다.

Files.CreateDirectories()를 사용하여 디렉토리 생성을 보여주는 Java의 예제 프로그램.

코드:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateDir {
public static void main(String[] args) throws IOException {
String Name = "C:\Users\admin\Desktop\newdir";
Path path1 = Paths.get(Name);
Files.createDirectories(path1);
}
}
로그인 후 복사

출력:

위 프로그램의 출력은 아래 형식과 같습니다.

위 예제를 실행하면 File.createDirectories를 사용하여 새로운 디렉터리가 생성됩니다.

PosixFilePermission 사용

PosixFilePermissions 메소드를 사용하여 권한을 설정하고 새 디렉토리를 생성할 수 있습니다. Windows 시스템에서는 이 클래스의 사용을 허용하지 않습니다.

코드:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
public class CreateDir {
public static void main(String[] args) throws IOException {
String Name = "C:\Users\admin\Desktop\newdir";
Path path1 = Paths.get(Name);
if (!Files.exists(path1)) {
Set<PosixFilePermission>permissions1=PosixFilePermissions.fromString("rwxr--r--");
FileAttribute<Set<PosixFilePermission>>fileAttributes=PosixFilePermissions.asFileAttribute(permissions1);
Files.createDirectory(path1, fileAttributes);
System.out.println("Creation of directory successful");
} else {
System.out.println("A directory with this name already exists");
}
}
}
로그인 후 복사

출력:

자바 디렉토리

Java 디렉토리의 메소드

디렉토리에 포함된 파일 및 디렉터리 목록을 나열하는 데는 다섯 가지 방법이 있습니다. 그들은:

1. 문자열[] 목록[]

문자열 배열은 String[] list[] 메소드를 사용하여 반환됩니다. 모든 파일의 이름과 디렉터리에 있는 디렉터리는 문자열 배열에 있습니다. 파일 이름과 디렉터리에 있는 모든 디렉터리만 필요한 경우 이 방법을 사용합니다.

2. 문자열[] 목록(파일 이름필터 필터)

문자열 배열은 String[] 목록[파일 이름 필터 필터] 메서드를 사용하여 반환됩니다. 디렉터리에 있는 모든 파일과 디렉터리는 문자열 배열에 있습니다. 지정된 필터는 필터링할 파일을 지정합니다. 디렉토리에 존재하는 파일 이름과 디렉토리를 필터링하고 싶을 때 이 방법을 사용합니다.

3. 파일[] 목록파일[]

파일의 객체 배열은 File[] listFiles[] 메소드를 사용하여 반환됩니다. 파일 크기를 확인하거나 절대 경로를 얻는 등 개별 디렉터리나 파일 디렉터리에 대한 작업을 하고 싶을 때 이 방법을 사용합니다.

4. 파일[] lisFiles(파일 이름필터 필터)

파일의 개체 배열은 File[] lisFiles(파일 이름 필터 필터) 메서드를 사용하여 반환되지만 지정된 필터는 지정된 파일을 필터링합니다. 이 방법을 사용하여 일부 필터로 파일 객체를 필터링합니다.

5. 파일[] 목록파일(파일필터 필터)

파일의 객체 배열은 File[] lisFiles(Filename Filter filter) ) 메서드를 사용하여 반환되지만 지정된 필터는 지정된 파일을 필터링합니다. 이 방법을 사용하여 일부 필터로 파일 객체를 필터링합니다.

임시 디렉토리 생성

CreateTempDirectory() 메소드는 Java에서 임시 디렉토리를 생성하는 데 사용됩니다. 이 메소드는 접두사가 지정된 Files 클래스에 속하며 속성을 추가할 수 있지만 이는 선택 사항입니다. 아래 프로그램은 Java로 임시 디렉토리를 생성하는 방법을 보여줍니다.

코드:

private void createDir() throws IOException {
Path temp = Files.createTempDirectory("C:\Users\admin\Desktop\newdir");
Path temp = Files.createTempFile(temp, "C:\Users\admin\Desktop\newdir", ".tmp");
List<String> lines1 = Arrays.asList("Line1", "Line2");
Files.write(temp, lines1, Charset.defaultCharset(), StandardOpenOption.WRITE);
System.out.printf("Content written to the temporary file %s%n", tempFile.toString());
}
로그인 후 복사

파일 쓰기 시연 프로그램

코드:

String dir = System.getProperty("C:\Users\admin\Desktop\newdir");
String file = "check.txt";
String Path = directory + File.separator + fileName;
// contents are written to the file
try(FileWriter fileWriter = new FileWriter(Path)) {
String Content = "This is a file.";
fileWriter.write(Content);
} catch (IOException e) {
// exceptions are handled
}
// contents are read from the file
try(FileReader fileReader = new FileReader(Path)) {
int cha = fileReader.read();
while(cha != -1) {
System.out.print((char)cha);
cha = fileReader.read();
}
} catch (FileNotFoundException e) {
// exceptions are handled
} catch (IOException e) {
// exceptions are handled
로그인 후 복사

출력:

자바 디렉토리

장점

장점은 아래와 같습니다.

  • 모든 프로젝트 또는 하위 프로젝트의 각 소스 코드에는 루트 디렉터리가 있습니다.
  • 디렉토리를 사용하여 이름에 충돌이 없습니다.
  • 컴파일하기 위해 파일을 나열할 필요는 없습니다. 도구가 작업을 수행하려면 루트 디렉터리를 알아야 합니다.
  • 포함된 리소스의 수가 검색 엔진 데이터베이스보다 적습니다.
  • 선택된 리소스는 디렉토리를 사용하여 평가, 주석 추가 또는 분류할 수 있습니다.
  • Java 디렉토리를 사용하면 관련 결과가 검색될 확률이 높아질 수 있습니다.

결론

이 튜토리얼에서는 디렉토리의 개념, 다양한 방법을 사용하여 Java에서 디렉토리 생성, Java에서 디렉토리 목록, 임시 디렉토리 생성, 디렉토리의 파일에 쓰기, Java에서 디렉토리의 장점 및 다양한 방법을 사용하여 Java에서 디렉토리를 생성하고 해당 출력 스냅샷과 함께 Java 디렉토리의 파일에 쓰는 방법을 보여주는 프로그래밍 예제입니다.

위 내용은 자바 디렉토리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!