안드로이드 파일 입출력 예제
파일 입출력을 할 때 내장 메모리 파일을 처리하는 경우와 외장 메모리(SD card) 파일을 처리하는 경우가 있습니다.
안드로이드에서 Byte 단위 처리를 할 때는
- FileInputStream/FileOutputStream
- BufferedInputStream/BufferedoutputStream
문자 단위 처리 할 때는
- FileReader/FileWiter
- BufferedReader/BufferedWriter
클래스를 사용합니다.
내장 메모리 파일 처리
내장 메모리 파일 쓰기
- 아래 코드에서 FileWriter의 첫 번째 인자인 getFilesDir()는 파일이 저장되는 디렉토리를 나타내는 경로입니다.
두 번째 인자가 true일 경우 기존 파일이 존재할 경우 이어쓰기를 하고 false일 경우 기존 파일이 존재할 경우 덮어쓰기를 합니다.
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(getFilesDir() + "test.txt", true));
bw.write("안녕하세요 Hello");
bw.close();
Toast.makeText(this,"저장완료", Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
내장 메모리 파일 읽기
- FileReader의 첫 번째 인자로 읽을 파일의 경로를 지정해줍니다.
readLine() 메소드는 줄 단위로 읽기 때문에 while문을 사용해서 끝까지 읽도록 해야합니다.
try{
BufferedReader br = new BufferedReader(new FileReader(getFilesDir()+"test.txt"));
String readStr = "";
String str = null;
while(((str = br.readLine()) != null)){
readStr += str +"\n";
}
br.close();
Toast.makeText(this, readStr.substring(0, readStr.length()-1), Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(this, "File not Found", Toast.LENGTH_SHORT).show();
}catch (IOException e) {
e.printStackTrace();
}
외장 메모리 파일 처리(SD cared)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
public void checkFunction(){
int permissioninfo = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(permissioninfo == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"SDCard 쓰기 권한 있음",Toast.LENGTH_SHORT).show();
}else{
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
}else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
String str = null;
if(requestCode == 100){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
str = "SD Card 쓰기권한 승인";
else str = "SD Card 쓰기권한 거부";
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
}
public String getExternalPath(){
String sdPath ="";
String ext = Environment.getExternalStorageState();
if(ext.equals(Environment.MEDIA_MOUNTED)){
sdPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
}else{
sdPath = getFilesDir() +"";
}
return sdPath;
}
외장 메모리 파일 처리
-외장 메모리 파일 처리는 내장 메모리 파일 처리하는 경우와 비슷합니다.
파일읽기
try{
String path = getExternalPath();
BufferedReader br = new BufferedReader(new FileReader(path+title));
String readStr = "";
String str = null;
while(((str = br.readLine()) != null)){
readStr += str +"\n";
}
br.close();
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(this, "File not Found", Toast.LENGTH_SHORT).show();
}catch (IOException e) {
e.printStackTrace();
}
파일쓰기
try{
String path = getExternalPath();
String filename = title;
BufferedWriter bw = new BufferedWriter(new FileWriter(path + filename, false));
bw.write("Hello");
bw.close();
Toast.makeText(this,"저장완료", Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
아래 예제는 파일 입출력을 사용한 예제입니다.
위 예제의 모든 코드는 깃허브에서 볼 수 있습니다.
https://github.com/Ywook/AndroidPractice9
'Android Studio' 카테고리의 다른 글
안드로이드 Handler, AsyncTask 사용하기 (0) | 2017.05.30 |
---|---|
안드로이드 Canvas, Paint 사용하기 (0) | 2017.05.23 |
안드로이드 웹 파일 저장 및 통신하기 (0) | 2017.05.09 |
안드로이드 웹뷰(WebView) 사용하기 (2) | 2017.05.09 |
안드로이드 CustomWidget 만들기 (0) | 2017.05.01 |