Java/Code snippet
[Java] 파일입출력 간단 쉬운 예제
2023. 1. 30. 00:33반응형
예제코드1. 파일 입력 예제
input_test.txt 파일을 bin폴더에다 만든다. 그리고 내용을 적당히 채워둔다.
※ 혹시 bin폴더가 안보인다면? 이 링크를 참고한다.
아래의 코드를 참고하여 실행한다.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class enter {
public static void main(String[] args) throws IOException {
String path = enter.class.getResource("").getPath();
System.out.println("path: " + path);
BufferedReader br = new BufferedReader(new FileReader(path + "/input_test.txt"));
while(true) {
String line = br.readLine();
if (line == null) break; // 읽었는데 아무 것도 없는 경우
System.out.println(line);
}
br.close();
}
}
출력화면:
path: /C:/git/AlgorithmStudy/2023_01_29_Java_Parsing/bin/
line1. helloworld
line2. nice to meet you
line3. Yes. I am fine.
br.read()함수를 활용하는 코드는 아래와 같다.
read()함수는 텍스트 파일에서 한 글자씩 글자를 읽어 하나의 char을 리턴하는 함수이다.
파일의 끝에 도달하면 (더 이상 읽을 글자가 없으면) -1을 리턴합니다.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class enter {
public static void main(String[] args) throws IOException {
String path = enter.class.getResource("").getPath();
System.out.println("path: " + path);
BufferedReader br = new BufferedReader(new FileReader(path + "/input_test.txt"));
int ch;
while ((ch = br.read()) != -1) {
System.out.print((char) ch);
}
br.close();
}
}
출력화면:
path: /C:/git/AlgorithmStudy/2023_01_29_Java_Parsing/bin/
line1. helloworld
line2. nice to meet you
line3. Yes. I am fine.
참고자료
반응형
'Java > Code snippet' 카테고리의 다른 글
[Java] 예제로 이해하기, anyMatch() 및 Stream() 활용 (0) | 2022.04.28 |
---|---|
[Java] 여러가지 코드들 (0) | 2021.07.28 |