try {
        	FileInputStream fin = new FileInputStream(fileName);
            ZipInputStream zin = new ZipInputStream(fin);

            byte[] buffer = new byte[1024];

            BufferedInputStream in = new BufferedInputStream(zin);
            
            ZipEntry ze = null;
            
            while ((ze = zin.getNextEntry()) != null) {
                
                FileOutputStream fout = new FileOutputStream(mContext.getFilesDir().getAbsolutePath()+"dir/" + ze.getName());
                BufferedOutputStream out = new BufferedOutputStream(fout);
                long c = 0;
                while ((c = in.read(buffer, 0, 1024)) != -1) {
                    out.write(buffer, 0, (int) c);
                }
                zin.closeEntry();
                out.close();
                fout.close();
            }
            
            in.close();
            zin.close();
        } catch (Exception e) {
        }
이렇게 하는겁니당 fileName에 zip의 상세경로를 넣어주고 dir에 원하는 폴더를 지정해주면 dir폴더에 압축파일이 풀리게 된다.
fileName예시 : 다운로드 받아 저장한 path/파일이름.zip






    	if ( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    		String path = Environment.getExternalStorageDirectory()+"/android/data/pe.berabue.maptools/.image";
    		File file = new File(path);

    		if( !file.exists() ) {// 원하는 경로에 폴더가 있는지 확인
    			file.mkdirs();

    			for ( int i = 0; i < 27; i++ ) {
    				byte [] buffer = new byte[8*1024];
    				int length = 0;
    				InputStream is = this.getResources().openRawResource(R.drawable.map1+i);  
    				BufferedInputStream bis = new BufferedInputStream(is);    

    				try {
    					FileOutputStream fos = new FileOutputStream(path+"/map"+(i+1)+".png");
    					while ((length = bis.read(buffer)) >= 0)
    						fos.write(buffer, 0, length);
    					fos.flush();  
    					fos.close();
    				} catch (Exception e) {} 
    			}
    		}
    	}

프로젝트 drawable 폴더안에 있는 png파일을 sdCard로 옮기는 방법.

먼저 sdCard가 연결이 되어 있는지 확인을 한다.
그리고 파일을 옮겨놓을 경로를 path에 입력을 시킨다.
원하는 경로의 폴더가 있는지 확인 후 없으면 새로 만들어준다.

for문이 28번 돌아가는 이유는 테스트할때 이미지가 28개였기때문에..

조금 변형시키면 raw폴더안 파일이나 다른 파일들도 충분히 이동 가능할듯!



'Android > File' 카테고리의 다른 글

ZipEntry를 활용한 압축해제  (0) 2013.06.02
단말기 내부에 폴더 및 txt파일 생성하기  (0) 2011.03.02
Sd Card 이미지 읽어오기  (0) 2011.02.14
txt 파일 읽어오기  (0) 2011.02.11
SD Card에 txt 파일로 저장하기  (0) 2011.02.05
		
		String dirPath = getFilesDir().getAbsolutePath(); 
		File file = new File(dirPath); 
		
		// 일치하는 폴더가 없으면 생성
		if( !file.exists() ) {
			file.mkdirs();
			Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
		}
		
		// txt 파일 생성
		String testStr = "ABCDEFGHIJK...";
		File savefile = new File(dirPath+"/test.txt");
		try{
			FileOutputStream fos = new FileOutputStream(savefile);
			fos.write(testStr.getBytes());
			fos.close();
			Toast.makeText(this, "Save Success", Toast.LENGTH_SHORT).show();
		} catch(IOException e){}
		
		// 파일이 1개 이상이면 파일 이름 출력
		if ( file.listFiles().length > 0 )
    		for ( File f : file.listFiles() ) {
    			String str = f.getName();
    			Log.v(null,"fileName : "+str);
    			
    			// 파일 내용 읽어오기
    			String loadPath = dirPath+"/"+str;
    			try {
    				FileInputStream fis = new FileInputStream(loadPath);
    			    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(fis));
    				
    			    String content="", temp="";
    				while( (temp = bufferReader.readLine()) != null ) {
    					content += temp;
    				}
    				Log.v(null,""+content);
    			} catch (Exception e) {}
    		}


LogCat 결과
		if ( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			String path = Environment.getExternalStorageDirectory()+"/android/data/pe.berabue.maptools/.image";

			File file = new File(path);
			String str;
			int num = 0;
			
			int imgCount = file.listFiles().length;	// 파일 총 갯수 얻어오기
			map = new Bitmap[imgCount];
				
			if ( file.listFiles().length > 0 )
				for ( File f : file.listFiles() ) {
					str = f.getName();				// 파일 이름 얻어오기
					map[num] = BitmapFactory.decodeFile(path+"/"+str);
					num++;
				}
		}
		FileInputStream fis = new FileInputStream(loadPath); // loadPath는 txt파일의 경로
		BufferedReader bufferReader = new BufferedReader(new InputStreamReader(fis));
				
		String str, str1="";
		String map[];

		while( (str = bufferReader.readLine()) != null )	// str에 txt파일의 한 라인을 읽어온다
			str1 += str;									// 읽어온 라인을 str1에 추가한다

		map = str1.split(",");								// 콤마(,)를 기준으로 map String 배열에 추가

		// 만약 0, 100, 123, 111, 122, 5 라면 map={0,100,123,111,122,5}
/* map log 저장 */
public void Save() {
  File file;
  String path = Environment.getExternalStorageDirectory()+"/android/data/pe.berabue.maptools/map";
  file = new File(path); 
  if( !file.exists() ) // 원하는 경로에 폴더가 있는지 확인
    file.mkdirs();
    
  file = new File(path+"/myTest11.txt");
  try{
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(mMapManager.PrintLog().getBytes());
    fos.close();
    Toast.makeText(context, "Save Success", Toast.LENGTH_SHORT).show();
  } catch(IOException e){}
} 

맵툴 제작에 사용중인 소스.

경로를 얻어와 폴더가 없으면 폴더를 생성하고 내용을 받아와 파일을 생성한다.

구현중 : 텍스트 파일 이름 입력받기, 저장된 파일 리스트뷰로 나타내기

먼저 SD Card에 사용을 위해 퍼미션을 줘야한다.

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


import java.io.*;
import android.app.*;
import android.os.*;
import android.widget.*;

public class SDTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        String str = Environment.getExternalStorageState();
        if str.equals(Environment.MEDIA_MOUNTED)) {
        
          String dirPath = "/sdcard/android/data/pe.berabue.sdtest/temp"
          File file = new File(dirPath)
          if!file.exists() )  // 원하는 경로에 폴더가 있는지 확인
            file.mkdirs();
        }
        else
          Toast.makeText(SDTest.this, "SD Card 인식 실패", Toast.LENGTH_SHORT).show();
    }
}



file.mkdirs()와 file.mkdir()의 차이점

mkdirs()는 원하는 경로의 상위 폴더가 없으면 상위 폴더까지 생성.
ex ) sdcard/android/data/aaa/bbb
bbb 폴더를 만드려는데 aaa폴더가 없다면 aaa 폴더까지 생성 한다.

mkdir()은 지정 폴더만 생성.



구글에서 권장하는 폴더명은

android/data/패키지명/폴더명 


+ Recent posts