자바 읽기 파일
파일 읽기
이전 장에서 파일을 만들고 쓰는 방법을 배웠습니다.
다음 예제에서는 Scanner
클래스를 사용하여 이전 장에서 만든 텍스트 파일의 내용을 읽습니다.
예시
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
출력은 다음과 같습니다.
Files in Java might be tricky, but it is fun enough!
파일 정보 가져오기
파일에 대한 자세한 정보를 얻으려면 다음 File
방법 중 하나를 사용하십시오.
예시
import java.io.File; // Import the File class
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
출력은 다음과 같습니다.
File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
참고: Java: 등의 파일을 읽고 쓰는 데 사용할 수 있는 Java API에는 사용 가능한 클래스가 많이 있습니다 FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream
. 사용할 Java 버전과 바이트 또는 문자를 읽어야 하는지 여부에 따라 다릅니다. 및 파일/라인 등의 크기
팁: 파일을 삭제하려면 Java 파일 삭제 장 을 읽으십시오 .