프로그래밍/안드로이드

안드로이드 - 파일 탐색기 만들기

가카리 2015. 11. 4. 21:16
반응형

파일 입출력 메소드는 파일 안에 저장된 데이터를 관리하는데 비해 파일 관리 메소드는 파일 그 자체가 관리 대상이다.

 

File 클래스의 다음 메소드는 파일의 목록을 구한다.

 

    String[] list([FilenameFilter filter])

    File[] listFiles([FilenameFilter filter])

 

파일의 경로 목록을 구할 수도 있고 File 객체의 목록을 구할 수도 있다.

 

filter를 지정하면 특정 조건에 맞는 파일의 목록만 조사하며 생략하면 모든 파일이 조사된다. 디렉터리도 같이 조사되지만 현재 디렉터리인 .과 부모 디렉터리인 ..은 제외된다.

만약 파일이 하나도 없으면 null이 리턴된다.

 

다음 메소드는 파일의 이름을 변경하거나 삭제한다.

 

    boolean renameTo(File newPath)

    boolean delete()

    void deleteOnExit()

 

둘 다 패키지 디렉터리 아래의 파일만 관리할 수 있으며 경로는 역시 사용할 수 없다. deleteOnExit는 가상 머신이 종료될 때 삭제하도록 예약하는 것이다.

 

다음 메소드는 파일에 대한 정보를 조사한다.

 

    boolean exists()

    boolean isFile()

    boolean isDirectory()    

    long length()

    boolean isHidden()

    long lastModified()

    boolean canRead()

    boolean canWrite()

 

디렉터리를 생성할 때는 다음 메소드를 사용한다.

    boolean mkdir()

    boolean mkdirs()

 

mkdir은 부모 폴더까지 생성하지 않는데 비해 mkdirs는 부모 폴더까지 한꺼번에 생성한다는 점이 다르다.

 

다음 예제는 SD카드의 파일과 디렉터리 목록을 보여준다.

 

 

SD카드를 사용하기 때문에 반드시 매니페스트 파일에 퍼미션을 추가해야한다.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.ch25_fileexplorer"

android:versionCode="1"

android:versionName="1.0" >

 

<uses-sdk

android:minSdkVersion="19"

android:targetSdkVersion="19" />

 

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".FileExplorer"

android:label="@string/app_name" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

 

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

</manifest>

 

 

fileexplorer.xml

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent"

>

 

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

>

 

<TextView

android:id="@+id/current"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="current"

/>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content">

<Button

android:id="@+id/btnroot"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="mOnClick"

android:text="Root"/>

<Button

android:id="@+id/btnup"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="mOnClick"

android:text="Up"/>

 

</LinearLayout>

</LinearLayout>

    <ListView

     android:id="@+id/filelist"

     android:layout_width="match_parent"

     android:layout_height="match_parent"

     />

 

</LinearLayout>

 

 

FileExplorer.java

 

package com.example.ch25_fileexplorer;

 

import java.io.File;

import java.util.ArrayList;

 

import android.app.Activity;

import android.os.Bundle;

import android.os.Environment;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.Toast;

 

 

public class FileExplorer extends Activity {

    String mCurrent;

    String mRoot;

    TextView mCurrentTxt;

    ListView mFileList;

    ArrayAdapter<String> mAdapter;

    ArrayList<String> arFiles;

      

    

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.fileexplorer);

      

        mCurrentTxt = (TextView)findViewById(R.id.current);

        mFileList = (ListView)findViewById(R.id.filelist);

        

        arFiles = new ArrayList<String>();

        //SD카드 루트 가져옴

        mRoot = Environment.getExternalStorageDirectory().getAbsolutePath();

        mCurrent = mRoot;

        

        //어댑터를 생성하고 연결해줌

        mAdapter = new ArrayAdapter<String>(this,

                android.R.layout.simple_list_item_1, arFiles);

        mFileList.setAdapter(mAdapter);//리스트뷰에 어댑터 연결

        mFileList.setOnItemClickListener(mItemClickListener);//리스너 연결

        

        refreshFiles();

        

    }

    

    //리스트뷰 클릭 리스너

    AdapterView.OnItemClickListener mItemClickListener =

            new AdapterView.OnItemClickListener() {

 

                @Override

                public void onItemClick(AdapterView<?> parent, View view,

                        int position, long id) {

                    // TODO Auto-generated method stub

                    String Name = arFiles.get(position);//클릭된 위치의 값을 가져옴

                    

                    //디렉토리이면

                    if(Name.startsWith("[") && Name.endsWith("]")){

                        Name = Name.substring(1, Name.length() - 1);//[]부분을 제거해줌

                    }

                    //들어가기 위해 / 터치한 파일 명을 붙여줌

                    String Path = mCurrent + "/" + Name;

                    File f = new File(Path);//File 클래스 생성

                    if(f.isDirectory()){//디렉토리면?

                        mCurrent = Path;//현재를 Path 바꿔줌

                        refreshFiles();//리프레쉬

                    }else{//디렉토리가 아니면 토스트 메세지를 뿌림

                    Toast.makeText(FileExplorer.this, arFiles.get(position), 0).show();

                }

            }

    };

    

    //버튼 2 클릭시

    public void mOnClick(View v){

        switch(v.getId()){

        case R.id.btnroot://루트로 가기

            if(mCurrent.compareTo(mRoot) != 0){//루트가 아니면 루트로 가기

                mCurrent = mRoot;

                refreshFiles();//리프레쉬

            }

            break;

        case R.id.btnup:

            if(mCurrent.compareTo(mRoot) != 0){//루트가 아니면

                int end = mCurrent.lastIndexOf("/");/// 나오는 마지막 인덱스를 찾고

                String uppath = mCurrent.substring(0, end);//그부분을 짤라버림 위로가게됨

                mCurrent = uppath;

                refreshFiles();//리프레쉬

            }

            break;

        }

    }

      

    

    void refreshFiles(){

        mCurrentTxt.setText(mCurrent);//현재 PATH 가져옴

        arFiles.clear();//배열리스트를 지움

        File current = new File(mCurrent);//현재 경로로 File클래스를 만듬

        String[] files = current.list();//현재 경로의 파일과 폴더 이름을 문자열 배열로 리턴

        

        //파일이 있다면?

        if(files != null){

            //여기서 출력을 해줌

            for(int i = 0; i < files.length;i++){

                String Path = mCurrent + "/" + files[i];

                String Name = "";

                

                File f = new File(Path);

                if(f.isDirectory()){

                    Name = "[" + files[i] + "]";//디렉토리면 [] 붙여주고

                }else{

                    Name = files[i];//파일이면 그냥 출력

                }

                

                arFiles.add(Name);//배열리스트에 추가해줌

            }

        }

        //다끝나면 리스트뷰를 갱신시킴

        mAdapter.notifyDataSetChanged();

    }

}

 

 

출력 화면

 

반응형