반응형
java txt file 읽기, java file read
txt file read
BufferedReader br = null;
String textFilePath = dbProps.getProperty("textfile.path");
br = new BufferedReader(new FileReader(textFilePath));
String line= "";
int size = 0;
while ((line = br.readLine()) != null) {
size++;
System.out.println("한줄씩 출력 [" + size + "] 라인 >> "+ line);
}
String textFilePath = dbProps.getProperty("textfile.path");
- dbProps.getProperty : property에 설정된 txt 파일 경로를 읽어 옵니다.
br = new BufferedReader(new FileReader(textFilePath));
- new FileReader(textFilePath)는 textFilePath 변수에 저장된 경로의 파일을 읽기 위해 FileReader라는 객체를 생성합니다. 이 객체는 파일로부터 문자 데이터를 읽어오는 역할
new BufferedReader()
- 생성된 FileReader 객체를 BufferedReader라는 객체로 감싸 데이터를 한 번에 모아서 읽기
while ((line = br.readLine()) != null) { }
- br.readLine()은 파일에서 한 줄의 텍스트를 읽어옵니다
실행
- 아래 처럼 출력을 확인할 수 있습니다.
전체 소스
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
private static final Properties dbProps = new Properties();
static {
try (InputStream input = Main.class.getClassLoader().getResourceAsStream("app.properties")) {
dbProps.load(input);
} catch (IOException ex) {
logger.error("app.properties 파일을 로드하는 데 실패했습니다.", ex);
throw new RuntimeException("설정 파일 로드 실패", ex);
}
}
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Runnable task = () -> {
BufferedReader br = null;
try {
// 텍스트 파일 읽기
String textFilePath = dbProps.getProperty("textfile.path");
br = new BufferedReader(new FileReader(textFilePath));
String line= "";
int size = 0;
while ((line = br.readLine()) != null) {
size++;
System.out.println("한줄씩 출력 [" + size + "] 라인 >> "+ line);
}
} catch (IOException e) { logger.error("텍스트 파일 읽기 오류 발생", e);
} finally {
try { if (br != null) br.close(); } catch (IOException e) { logger.error("BufferedReader close Exception 발생", e); }
}
};
scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
scheduler.shutdown();
}
}
}
반응형
'dev > java 배포' 카테고리의 다른 글
java mssql to file #008 (0) | 2025.05.06 |
---|---|
java file read db 저장 #007 (0) | 2025.05.01 |
java properties 조회 #005 (0) | 2025.04.29 |
java 실행 스케줄러 #003 (0) | 2025.04.29 |
[JAVA] TimeUnit (0) | 2025.04.29 |