Java 프로그래밍의 가장 기초적인 파일 및 디렉터리 작업 방법 상세 정보
일반적으로 JAVA를 사용하여 파일을 읽고 쓰는 등의 작업을 자주 하는데, 여기서 자주 사용하는 파일 작업을 요약합니다.
1. 파일 만들기
public static boolean createFile(String filePath){
boolean result = false;
File file = new File(filePath);
if(!file.exists()){
try {
result = file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
2. 폴더 만들기
public static boolean createDirectory(String directory){
boolean result = false;
File file = new File(directory);
if(!file.exists()){
result = file.mkdirs();
}
return result;
}
3. 파일 삭제
public static boolean deleteFile(String filePath){
boolean result = false;
File file = new File(filePath);
if(file.exists() && file.isFile()){
result = file.delete();
}
return result;
}
4. 폴더 삭제폴더 아래의 하위 파일 및 폴더 차례로 삭제
public static void deleteDirectory(String filePath){
File file = new File(filePath);
if(!file.exists()){
return;
}
if(file.isFile()){
file.delete();
}else if(file.isDirectory()){
File[] files = file.listFiles();
for (File myfile : files) {
deleteDirectory(filePath + "/" + myfile.getName());
}
file.delete();
}
}
5. 파일 읽기(1) 바이트 단위로 파일을 읽고 그림, 소리, 영상 등 바이너리 파일을 읽는 데 자주 쓰인다
public static String readFileByBytes(String filePath){
File file = new File(filePath);
if(!file.exists() || !file.isFile()){
return null;
}
StringBuffer content = new StringBuffer();
try {
byte[] temp = new byte[1024];
FileInputStream fileInputStream = new FileInputStream(file);
while(fileInputStream.read(temp) != -1){
content.append(new String(temp));
temp = new byte[1024];
}
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
(2) 문자 단위로 파일 읽기, 텍스트, 숫자 등 유형의 파일 읽기, 중국어 읽기 지원
public static String readFileByChars(String filePath){
File file = new File(filePath);
if(!file.exists() || !file.isFile()){
return null;
}
StringBuffer content = new StringBuffer();
try {
char[] temp = new char[1024];
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
while(inputStreamReader.read(temp) != -1){
content.append(new String(temp));
temp = new char[1024];
}
fileInputStream.close();
inputStreamReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
(3) 비헤이비어 단위로 파일 읽기, 행 포맷 파일 읽기
public static List<String> readFileByLines(String filePath){
File file = new File(filePath);
if(!file.exists() || !file.isFile()){
return null;
}
List<String> content = new ArrayList<String>();
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
BufferedReader reader = new BufferedReader(inputStreamReader);
String lineContent = "";
while ((lineContent = reader.readLine()) != null) {
content.add(lineContent);
System.out.println(lineContent);
}
fileInputStream.close();
inputStreamReader.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
6. 파일 쓰기문자열이 파일에 쓰는 몇 가지 종류 중 FileWriter 효율이 가장 높고, Buffered OutputStream 다음으로 FileOutputStream이 가장 나쁘다.
(1) FileOutputStream을 통해 파일 쓰기
public static void writeFileByFileOutputStream(String filePath, String content) throws IOException{
File file = new File(filePath);
synchronized (file) {
FileOutputStream fos = new FileOutputStream(filePath);
fos.write(content.getBytes("GBK"));
fos.close();
}
}
(2) BufferedOutputStream을 통해 파일 쓰기
public static void writeFileByBufferedOutputStream(String filePath, String content) throws IOException{
File file = new File(filePath);
synchronized (file) {
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(filePath));
fos.write(content.getBytes("GBK"));
fos.flush();
fos.close();
}
}
(3) FileWriter를 통해 문자열을 파일에 쓰기
public static void writeFileByFileWriter(String filePath, String content) throws IOException{
File file = new File(filePath);
synchronized (file) {
FileWriter fw = new FileWriter(filePath);
fw.write(content);
fw.close();
}
}
디렉토리 작업디렉터리는 다른 파일과 디렉터리를 포함할 수 있는 파일의 목록입니다.디렉터리에 사용할 수 있는 파일 목록을 열거하려면 File 대상을 사용하여 디렉터리를 만들고 File 대상에서 호출할 수 있는 모든 방법과 디렉터리에 대한 방법 목록을 얻을 수 있습니다.
디렉토리 만들기
여기에는 디렉토리를 만들 수 있는 두 가지 유용한 파일 방법이 있습니다.
mkdir () 방법으로 디렉터리를 만들었습니다.true를 성공적으로 되돌렸습니다.false를 되돌렸습니다.실패는 전체 경로가 존재하지 않기 때문에 파일 대상의 경로가 이미 존재하거나 디렉터리를 만들 수 없다는 것을 가리킨다.
mkdirs () 방법은 디렉터리와 상급 디렉터리를 만듭니다.
다음 예제에서는'/tmp/user/java/bin'디렉터리를 만듭니다.
import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
위 코드를 컴파일하여 "/tmp/user/java/bin"을 만듭니다.팁: Java는 자동으로 UNIX와 Windows 규약에 따라 경로 구분자를 처리합니다.Windows 버전의 Java에서 정사각형(/)을 사용하는 경우에도 올바른 경로를 사용할 수 있습니다.
카탈로그 목록
다음은 파일 대상이 제공하는list () 방법으로 디렉터리에 사용할 수 있는 모든 파일과 디렉터리를 표시할 수 있습니다
import java.io.File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try{
// create new file object
file = new File("/tmp");
// array of files and directory
paths = file.list();
// for each name in the path array
for(String path:paths)
{
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
}
당신/tmp 디렉터리에서 사용할 수 있는 디렉터리와 파일을 기반으로 다음 결과가 발생합니다.
test1.txt
test2.txt
ReadDir.java
ReadDir.class
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.