오늘은 apache commons-io 라이브러리를 활용해 파일 데이터 읽기, 쓰기 예시를 만들어 보겠습니다.
apache commons-io 라이브러리는 입출력 관련 유틸리티 기능을 제공하는 라이브러리 입니다.
InputStream/OutputStream, 파일 복사,수정, 파일 검색 필터링 등 입출력 관련 기능들을 쉽게 사용할 수 있도록 지원해줍니다.
그래들 설정
=> 모듈 수준의 build.gradle 파일 에서 commons-io 라이브러리를 추가해주세요. 버전은 아래의 공식홈페이지 정보를 참고하세요.
https://commons.apache.org/proper/commons-io/changes.html
Apache Commons IO Release Notes – Apache Commons IO
Apache Commons IO Release Notes Release History Version Date Description 2.19.0 2025-04-08 Version 2.19.0: Java 8 is required. 2.18.0 2024-11-16 Version 2.18.0: Java 8 is required. 2.17.0 2024-09-15 Version 2.17.0: Java 8 is required. 2.16.1 2024-04-04 Jav
commons.apache.org
예시에 활용할 폴더 및 파일 생성
=> assets 폴더와 예시에 활용할 텍스트 파일을 생성해주세요. 그리고 텍스트파일에 내용을 입력하고 저장해주세요.저는 위 이미지와 같이 폴더 및 파일을 생성하고 내용을 입력하였습니다.
레이아웃 xml 파일 코드(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Commons IO 테스트"
android:textSize="20sp"
android:layout_marginBottom="20dp" />
<Button
android:id="@+id/btnReadAsset"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Asset 파일 읽기"
android:layout_marginBottom="10dp" />
<Button
android:id="@+id/btnWriteFile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="파일 쓰기/읽기"
android:layout_marginBottom="10dp" />
<Button
android:id="@+id/btnCopyFile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="파일 복사"
android:layout_marginBottom="10dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="20dp">
<TextView
android:id="@+id/tvLog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="로그가 여기에 표시됩니다."
android:textSize="12sp"
android:fontFamily="monospace"
android:padding="10dp"
android:background="#f0f0f0" />
</ScrollView>
</LinearLayout>
액티비티 자바 코드
public class MainActivity extends AppCompatActivity {
// 로그를 표시할 TextView 참조 변수
private TextView tvLog;
// 로그 텍스트를 누적해서 저장할 StringBuilder
private StringBuilder logText = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// XML의 뷰들을 찾아서 변수에 연결
tvLog = findViewById(R.id.tvLog);
Button btnReadAsset = findViewById(R.id.btnReadAsset);
Button btnWriteFile = findViewById(R.id.btnWriteFile);
Button btnCopyFile = findViewById(R.id.btnCopyFile);
// 각 버튼에 클릭 리스너 설정 (람다식 사용)
btnReadAsset.setOnClickListener(v -> readAssetFile());
btnWriteFile.setOnClickListener(v -> writeToInternalStorage());
btnCopyFile.setOnClickListener(v -> copyFileExample());
}
// 로그 메시지를 화면에 추가하는 메서드
private void addLog(String message) {
// 기존 로그에 새 메시지 추가
logText.append(message).append("\n");
// TextView에 업데이트된 로그 표시
tvLog.setText(logText.toString());
}
// assets 폴더의 파일을 읽는 메서드
private void readAssetFile() {
try {
// assets 폴더에서 sample.txt 파일을 InputStream으로 열기
InputStream is = getAssets().open("sample.txt");
// Commons IO를 사용해서 InputStream을 String으로 한번에 변환
String content = IOUtils.toString(is, "UTF-8");
// 스트림을 안전하게 닫기 (null 체크 포함)
IOUtils.closeQuietly(is);
addLog("Asset 파일 읽기 성공");
addLog("내용\n" + content);
} catch (IOException e) {
// 파일 읽기 실패시 에러 메시지 표시
addLog("Asset 파일 읽기 실패\n" + e.getMessage());
}
addLog("==========\n");
tvLog.setText(logText.toString());
}
// 내부 저장소에 파일을 쓰고 읽는 메서드
private void writeToInternalStorage() {
try {
// 앱 내부 저장소에 파일 객체 생성
File file = new File(getFilesDir(), "sample2.txt");
String data = "Commons IO로 저장한 데이터입니다.";
// Commons IO를 사용해서 파일에 문자열을 한번에 쓰기
FileUtils.writeStringToFile(file, data, "UTF-8");
addLog("파일 저장 완료\n" + file.getPath());
// Commons IO를 사용해서 파일 내용을 한번에 읽기
String readData = FileUtils.readFileToString(file, "UTF-8");
addLog("저장된 데이터\n" + readData);
} catch (IOException e) {
addLog("파일 처리 실패\n" + e.getMessage());
}
addLog("==========\n");
tvLog.setText(logText.toString());
}
// 파일을 복사하는 메서드
private void copyFileExample() {
try {
// writeToInternalStorage를 활용해 생성한 내부저장소의 원본 파일, 복사될 파일 가리킬 객체 생성
File sourceFile = new File(getFilesDir(), "sample2.txt");
File destFile = new File(getFilesDir(), "copied_sample.txt");
// 원본 파일이 존재하는지 확인
if (sourceFile.exists()) {
// Commons IO를 사용해서 파일을 한번에 복사
FileUtils.copyFile(sourceFile, destFile);
addLog("파일 복사 완료");
// Commons IO를 사용해서 파일 크기 확인
long size = FileUtils.sizeOf(destFile);
addLog("복사된 파일 크기\n" + size + " bytes");
} else {
addLog("원본 파일이 없습니다. 먼저 '파일 쓰기/읽기'를 눌러주세요.");
}
} catch (IOException e) {
addLog("파일 복사 실패\n" + e.getMessage());
}
addLog("==========\n");
tvLog.setText(logText.toString());
}
}
실행 결과
파일 읽기, 생성 및 쓰기, 복사가 되는 것을 볼 수 있습니다.
'안드로이드 자바' 카테고리의 다른 글
[Java][Android] Sharesheet 방식으로 데이터 공유하기 (0) | 2025.06.03 |
---|---|
[Java][Android] 버튼 연속 클릭 방지하기 (2) | 2025.06.02 |
[Java][Android] 암시적 인텐트로 지도 활용하기 (2) | 2025.05.27 |
[Java][Android] SharedPreferences 데이터 암호화 (0) | 2025.05.26 |
[Java][Android] LifecycleOwner 활용 예시 만들기 (2) | 2025.05.23 |