Java 파일 작성 및 쓰기
파일 생성
Java에서 파일을 생성하려면 이 방법을 사용할 수 있습니다 createNewFile()
. 이 메서드는 부울 값을 반환합니다. true
파일이 성공적으로 생성된 false
경우와 파일이 이미 존재하는 경우. 메서드는 try...catch
블록으로 묶여 있습니다. IOException
이것은 오류가 발생하면(어떤 이유로 파일을 생성할 수 없는 경우) throw하기 때문에 필요 합니다.
예시
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
출력은 다음과 같습니다.
File created: filename.txt
특정 디렉토리에 파일을 생성하려면(권한 필요), 파일의 경로를 지정하고 이중 백슬래시를 사용하여 " \
" 문자를 이스케이프합니다(Windows의 경우). Mac 및 Linux에서는 다음과 같이 경로를 작성할 수 있습니다. /Users/name/filename.txt
예시
File myObj = new File("C:\\Users\\MyName\\filename.txt");
파일에 쓰기
다음 예제에서는 FileWriter
클래스를 메서드와 함께 사용하여 write()
위 예제에서 만든 파일에 일부 텍스트를 씁니다. 파일 쓰기가 끝나면 다음 close()
방법으로 닫아야 합니다.
예시
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
출력은 다음과 같습니다.
Successfully wrote to the file.
위의 파일을 읽으려면 Java 파일 읽기 장으로 이동하십시오.