본문 바로가기
Android

Android FileList 파일 탐색기

by 캡틴노랑이 2021. 4. 4.
반응형

안드로이드 파일 탐색기

중간에 필터로 걸린 부분있으나.. 강제로 모든 파일 조회되게 변경해 놓음.

FileTreeListViewAdapter에서 파일 선택하는 부분은, 폴더, 파일 이미지 인터넷이나 개인이 사용하는 이미지 사용바람.

따로 올려 놓지 않음. 저작권 문제가 있을 수 있어서...

 

*주의사항  external  저장장치와 SD card는 착각하면 안된다... 

네이밍도 그지같이 해 놓음. ㅡㅡ;

 

 

 

 

 

test device : note 4

android os : Marshmallow 6.0

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FileTreeActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/tbToolBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
            app:title="File Tree" />
        <TextView
            android:id="@+id/tvPath"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="" />
        <ListView
            android:id="@+id/lvListView"
            android:layout_width="match_parent"
            android:layout_height="500dp" >
        </ListView>
 
 
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>    

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package com.example.sampleproject;
 
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
 
import android.Manifest;
 
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
 
import com.example.sampleproject.Data.FileData;
import com.example.sampleproject.Norang.NorangActivity;
 
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
public class FileTreeActivity extends NorangActivity {
 
    private TextView tvPath;
    private ListView lvListView;
    private FileTreeListViewAdapter adp;
 
    private String strCurrentDirectory = "";    //현재 path
    private String strCurrentFolder = "";       //현재 folder
    private int nPathlevel = 0;                 //path level root를 찾기 위함.
 
    private Comparator<FileData> folderNfileSorting = new Comparator<FileData>() {
        @Override
        public int compare(FileData data1, FileData data2) {
            int result ;
 
            if (data1.getIsFile() < data2.getIsFile())
                result = -1;
            else if (data1.getIsFile() == data2.getIsFile())
                result = data1.getName().compareTo(data2.getName()) ;
            else
                result = 1;
 
            return result ;
        }
    } ;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_tree);
 
        checkPermission();
        InitializeControl();
        InitializeCommonDataBind();
 
        ListView();
    }
 
    private void InitializeCommonDataBind() {
        //arrFileData = new ArrayList<FileData>();
    }
 
    private void InitializeControl() {
        toolbar = findViewById(R.id.tbToolBar);
        setToolbar("");
 
        lvListView = (ListView)findViewById(R.id.lvListView);
        tvPath = findViewById(R.id.tvPath);
    }
 
    public void checkPermission() {
 
        //파일 읽어도 되는지 권한 요청.
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)) {
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
            }
        }
    }
 
    private ArrayList<FileData> SearchFileSystem(String directoryPath)
    {
        ArrayList<FileData> arrFileData = new ArrayList<FileData>();
 
        if(directoryPath.equals(""))//root
        {
            //외부 저장장치와 sd카드와 혼동하면 안됨.
            //String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"  + strFolderName;  //외부 저장장치
            //String path = Environment.getRootDirectory().getAbsolutePath(); //system 하위 목록 표시.
            //String path = Environment.getDataDirectory().getAbsolutePath();//data directory
            //String pathExt = Environment.getExternalStorageState();
 
            String path =Environment.getExternalStorageDirectory().getAbsolutePath();//내부 저장소 /storage/emulated/0
 
            File[] rootDir = getExternalFilesDirs(null); //둘다 나옴. 단... 이 앱의 저장경로 full로 나옴.
            // /storage/emulated/0/Android/data/com.example.sampleproject/files     /storage/emulated/0
            // /storage/2E34-1334/Android/data/com.example.sampleproject/files      /storage/2E34-1334
 
            //root
            //for(File f : rootDir)
            for(int i=0; i < rootDir.length; i++)
            {
                //String strName = rootDir[i].getAbsolutePath().replace("/Android/data/" +  getPackageName() + "/files", "");
                String strName =  i == 0 ? "Device Storage" : "SD Card";
                String strFullDir = rootDir[i].getAbsolutePath().replace("/Android/data/" +  getPackageName() + "/files", "");
                FileData fd = new FileData(strName, strFullDir, 0);
                arrFileData.add(fd);
            }
        }
        else//하위 directory
        {
            Log.d("Data", directoryPath);//로그 남기기
 
            File directory = new File(directoryPath);
            File[] files = directory.listFiles();
 
            for (File f : files) {
                String strName = f.getName();
                String strFullDir = f.getAbsolutePath();
 
                FileData fd;
 
                //file filter  이 정도만 BMP GIF JPG PNG
                if(f.isFile()) // 0 폴더, 1 파일
                {
                    if (1==1)
                        fd = new FileData(strName, strFullDir, 1);
                    //only image
                    else if(f.getPath().endsWith(".bmp") || f.getPath().endsWith(".gif")|| f.getPath().endsWith(".jpg") || f.getPath().endsWith(".jpeg") || f.getPath().endsWith(".png"))
                        fd = new FileData(strName, strFullDir, 1);
                    else if (1==1)
                        fd = new FileData(strName, strFullDir, 1);
                    else
                        continue;
                }
                else //folder
                    fd = new FileData(strName, strFullDir, 0);
                }
 
                arrFileData.add(fd);
            }
        }
 
        return arrFileData;
 
        /*//확인용
        //내부 저장소소
        File directory = new File("/storage/emulated/0");
        File[] files = directory.listFiles();
 
        List<String> filesList = new ArrayList<>();
 
        for (int i=0; i< files.length; i++) {
            filesList.add(files[i].getName());
        }
 
        for(String s : filesList)
            tvTest.setText(tvTest.getText() + s + "\r\n");
        */
    }
 
    protected void ListView()
    {
        adp = new FileTreeListViewAdapter(SearchFileSystem(""));
        lvListView.setAdapter(adp);
 
        //리스트뷰의 아이템을 클릭시 해당 아이템의 문자열을 가져오기 위한 처리
        lvListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                ArrayList<FileData> arrFileSub = new ArrayList<FileData>();
 
                tvPath.setText( tvPath.getText() +  "/" + ((FileData)adapterView.getItemAtPosition(position)).getName());
 
                if(((FileData)adapterView.getItemAtPosition(position)).getIsFile() == 1) // 0 폴더, 1 파일
                    return;
 
                //이동 전 path  저장
                strCurrentDirectory = ((FileData)adapterView.getItemAtPosition(position)).getFullDir(); //빼고 넣기
                strCurrentFolder = ((FileData)adapterView.getItemAtPosition(position)).getName();
                nPathlevel++; //root를 알기 위해서.
                Log.d("path1", strCurrentDirectory);
                Log.d("path2", String.valueOf(nPathlevel));
 
 
                ArrayList<FileData> arrFileData = SearchFileSystem(((FileData)adapterView.getItemAtPosition(position)).getFullDir());//하위 경로 가져오기.
 
                Collections.sort(arrFileData, folderNfileSorting) ; //상단에 정의
 
                FileTreeListViewAdapter adpSub = new FileTreeListViewAdapter(arrFileData);
                lvListView.setAdapter(adpSub);
            }
        });
    }
 
    //홈버튼에서 뒤로 클릭시 이전 폴더로 가기 root에서는 기존 로직
    @Override
    public void onBackPressed() {//뒤로 가기 버튼
        //이전 폴더로..
 
        if(nPathlevel > 0) {
 
            nPathlevel--;
 
            tvPath.setText(SubString((String) tvPath.getText()));
            strCurrentDirectory = SubString(strCurrentDirectory);//이전 폴더 path로 변경
 
            //Log.d("Backpath1", path);
            //Log.d("Backpath2", String.valueOf(nPathlevel));
 
            ArrayList<FileData> arrFileData = SearchFileSystem(nPathlevel == 0 ? "" : strCurrentDirectory);
            Collections.sort(arrFileData, folderNfileSorting); //상단에 정의
 
            FileTreeListViewAdapter adpSub = new FileTreeListViewAdapter(arrFileData);
            lvListView.setAdapter(adpSub);
 
        }
        else {
            finish();
            //super.onBackPressed();
        }
    }
 
    //path 문자열 짜르기 마지막 folder 제거
    protected String SubString(String target)
    {
        String[] arrPath = target.split("/");
        String result = "";
 
        for(int i = 1; i < arrPath.length - 1; i++ )
            result += "/" + arrPath[i];
 
        return result;
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.example.sampleproject;
 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
 
import com.example.sampleproject.Data.FileData;
 
import java.util.ArrayList;
 
public class FileTreeListViewAdapter   extends BaseAdapter {
    private ArrayList<FileData> listViewItemList;
     
    public FileTreeListViewAdapter() {}
 
    public FileTreeListViewAdapter(ArrayList<FileData> arrFileData) {
        listViewItemList = arrFileData;
    }
     
    @Override
    public int getCount() {
        return listViewItemList.size() ;
    }
     
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final int pos = position;
        final Context context = parent.getContext();
         
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_view_filetree_adapter, parent, false);
        }
         
        ImageView ivPic = convertView.findViewById(R.id.ivPic);
        TextView tvName = convertView.findViewById(R.id.tvName) ;
        //TextView tvCnt = (TextView) convertView.findViewById(R.id.tvCnt) ;
 
        FileData listViewItem = listViewItemList.get(position);
 
         
        ivPic.setImageResource(listViewItem.getIsFile() == 1 ? R.drawable.images : R.drawable.folder);
        tvName.setText(listViewItem.getName());
        //tvCnt.setText(Integer.toString(listViewItem.getType()));
 
        return convertView;
    }
     
    @Override
    public long getItemId(int position) {
        return position ;
    }
     
    @Override
    public Object getItem(int position) {
        return listViewItemList.get(position) ;
    }   
     
    public void addItem(String name, int isFile) {
        FileData item = new FileData();
 
        item.setName(name);
        item.setIsFile(isFile);
 
        listViewItemList.add(item);
    }
 
}

 

 

 

 

반응형