상세 컨텐츠

본문 제목

[안드로이드] android asset에서 파일 읽기

스마트기기개발관련/안드로이드 개발

by AlrepondTech 2020. 9. 21. 03:13

본문

반응형

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

출처: http://www.masterqna.com/android/16945/assets-%ED%8F%B4%EB%8D%94-%EB%82%B4%EC%9D%98-db-%ED%8C%8C%EC%9D%BC-%EC%9D%BD%EA%B8%B0-%EC%93%B0%EA%B8%B0

assets 폴더 내의 DB 파일 읽기,쓰기

assets 폴더 내에 이미 다른 앱으로 만들어둔 sqlite 파일을 저장하고, 현재 앱에서는 이 파일..

그러니까 경로는 대강 /data/data/패키지명/assets/filename 이렇게 되겠네요.. 이걸 열어서 지지고 볶고 가능한지요?;

대충 해보니 안 되는거 같기도 하고... 정확한 답변 알고계신분 좀 알려주세요~

----------------------------------------------------------------------------------------------------------------

 

채택된 답변

asset 폴더는 안드로이드파일중에서 컴파일이 필요없는 파일들이나 직접 그 폴더로 엑세스 해서 디렉토리탐를탐색해 바assetmanager클래스를 이용해서 읽고 쓰고 지우고 할수있는용도로 알고있구요

자세한 설명은 https://developer.android.com/tools/projects/index.html

 

저기 asset에 db를 넣어놓고 /data/data/packageName/databases 로 파일복사를 하는건 안드로이드 Sqlite에서 db커넥션 권한이 외부에서는 커넥션을 못하게하도록 해 자기 apk경로의 폴더로 옮겨놓고 접속을 하는걸로 알고있습니다.( 개인관리용) 

http://developer.android.com/reference/android/database/package-summary.html

http://developer.android.com/reference/android/database/sqlite/package-summary.html

bangbang (8,220 포인트) 님이 2013년 12월 11일 답변 
인연님이 2013년 12월 11일 채택됨

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

assets경로에 있는 파일은 참조만 가능 한것으로 알고있습니다.
 

내용을 변경을 하려면 변경이 가능한 다른 위치로 복사를 하고 사용을 하시면 됩니다.

(예: SDCARD영역, database용폴더 등)

이라슈 (4,280 포인트) 님이 2013년 12월 10일 답변

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

public void CopyDB(String DBname) {

    AssetManager assetManager = this.getResources().getAssets();

    File outfile = new File(ROOT_DIR + DBname);

    InputStream is = null;

    FileOutputStream fo = null;

    long filesize = 0;

    try {

        is = assetManager.open(DBname, AssetManager.ACCESS_BUFFER);

        filesize = is.available();

        if (outfile.length() <= 0)

        {

            byte[] tempdata = new byte[(int) filesize];

            is.read(tempdata);

            is.close();

            outfile.createNewFile();

            fo = new FileOutputStream(outfile);

            fo.write(tempdata);

            fo.close();

        }

    } catch (IOException e)

    {

    }

}

이런식으로 에셋에있는 db파일을 복사하셔서 쓰시면 사용가능합니다.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

=================================

=================================

=================================

 

 

출처: http://ememomo.tistory.com/entry/asset-%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-txt-%EB%AC%B8%EC%84%9C-%EC%9D%BD%EA%B8%B0

어플을 만들때, 일일이 String으로 글을 적어 넣기도 하지만, 약관이나 정책등 이미 정의된 문서가 있을경우 이자체를 파일로 

바로 읽어 드려도 될것이다. 다시 일일이 치려면,, 노가다일 뿐이니..

간단하게 Asset에서 File을 읽어 드리는 방법에대해 소개 하고자 한다. 

 



이부분에 읽어 들일 파일을 넣고, 파일의 내용은 이렇다. 

"아니 왜 카톡에 답이 없어?"

며칠전, 무료문자 서비스 카카오톡을 자주 이용하는 친구에게서 전화가 왔다. 문자 마니아인 친구의 '목소리'를 오랜만에 듣는 터라 반가웠지만, 대화내용은 요즘 내가 자신의 문자를 '씹는다'는 타박이었다.

"어? 정말? 아닌데… 나도 카톡할 줄 안다고. 근데 안왔어. 안그래도 요즘 통 보내는 사람이 없던데."

나도 할 말이 있다고 투덜대며 카톡을 실행시키는 순간, '주르륵' 채팅 메시지가 떴다. 이미 한참 지난 날짜에 지인들이 보낸 메시지들이다. 물론 친구의 메시지도 있었다.

"내 카톡이 고장났나봐, 왜 바로바로 안떴지?"라는 내 순진한 질문에 친구는 "푸시 꺼놓은 것 아니냐"는 답변을 내놨다.

'아…푸시(push)'. 어렴풋이 그런 기능이 스마트폰에 있다는 생각이 났다. 그리고 얼마전 얼떨결에 깔아놓은 앱들이 그야말로 '밀어내는 알림'이 너무 많아 메뉴에서 뭔가를 꺼놨다는 기억이 났다.

아니나 다를까. 아이폰의 '설정→알림'으로 들어가니 모든 응용프로그램(앱)에 대한 소리, 경고, 화면 알림 표시가 비활성화돼 있었다. 개별 앱에 대해서만 따로 켜거나 꺼두면 될 것을, 무심코 통째로 꺼 둔 거였다. 최근 카톡 뿐 아니라 아침마다 단잠을 깨우던 뉴스 앱 업데이트 알림이 뜨지 않았던 이유가 있었다.

'푸시 알림'은 실시간 메시지를 통해 일정이나 메시지 전송 여부를 알려주는 기능을 한다. 카톡 문자나 언론사 앱 뉴스 업데이트 등을 알려주는 식이다. 푸시알림을 지원하는 앱도 있고 그렇지 않은 앱도 있다.

'푸시알림'을 지원하는 앱의 경우 설치 뒤 실행하면 푸시알림 허용 여부를 물어보는 창이 뜬다. 허용을 하면 그 앱에서 나오는 알림이나 정보를 실시간 알려주고, 허용하지 않으면 본인이 그 앱을 열어 실행시켜야 데이터 업데이트를 통해 새로운 소식을 알 수 있다.

내가 항상 스마트폰을 쳐다보지 않아도 뭔가 새로운 것을 알려준다는 점에서 '푸시' 기능은 분명 유용하다. 하지만 수많은 앱들이 불필요하게 '딩동딩동' 푸시 알람을 울려대면 자칫 공해로 느껴질 수 있다. 해당 앱이 통신망과 항상 연결돼있어야 하기 때문에 통신망에 부담을 주기도 한다.

'푸시알림'은 와이파이에서는 과금되지 않지만 3G통신에서는 거의 느낄 수 없을 정도의 소량 요금이 부과된다.

'푸시' 공해가 싫다면 '설정-알림' 탭에서 평소 손이 자주 가는 앱이 무엇인지 잘 고려해 각 앱별로 허용·비허용을 다시한번 정리하는 것도 좋겠다. 

<IT정보 펌글>

이에 대해 안드로이드에서 읽어 오려면~ 코드를 살펴 보자.

package com.ememomo;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ReadTextFromAsset extends Activity {

 private String assetTxt;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  
  setContentView(R.layout.main);
  TextView text = (TextView)findViewById(R.id.text);
  
  try {
   assetTxt = readText("pushpush.txt");
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  text.setText(assetTxt);
 }

 private String readText(String file) throws IOException {
  InputStream is = getAssets().open(file);

  int size = is.available();
  byte[] buffer = new byte[size];
  is.read(buffer);
  is.close();

  String text = new String(buffer);

  return text;
 }
}



간단하게 readText() 함수내에 파일 이름을 지정해 주면 된다.~ 

별 내용없으니 설명은 생략 하겠다.

실행 화면

 

=================================

=================================

=================================

 

 

출처: http://www.hoyanet.pe.kr/1971

 

프로그램안에서 사용해야 할 다량의 문자열들을 정의하는데 있어서 효율적인 방법은 소스코드에 모든 내용을 포함시키기 보다는 외부에 내용을 저장해 놓고 필요할 때 마다 읽어오는 방법입니다.

안드로이드에서는 문자열로서 사용하기 위한 데이터를 보관하기 위한 기법으로 리소스 XML에 내용을 기술하는 방법과 SQLite를 사용하는 방법, 그리고 assets 디렉토리를 사용하는 방법을 제공해 주고 있습니다.

오늘 소개할 내용은 assets 디렉토리에 저장된 텍스트 파일을 프로그램내로 읽어들이는 내용입니다.

assets 디렉토리

 

AssetManager의 객체 생성안드로이드 프로젝트를 이클립스 상에서 보면 assets라는 (평소에는 잘 사용하지 않는) 디렉토리에 있습니다. 프로그램과 직접적으로 연관되지 않은 비 리소스 파일들을 저장해 놓고 필요한 경우 스트림을 생성하여 읽어들이기 위한 저장공간입니다.

이 폴더안에 test.txt라는 파일을 넣었다고 가정하고 이 파일의 내용을 프로그램의 Runtime시에 읽어오는 방법을 소개하겠습니다.


Context 클래스 내에 보면 getResource()라는 메소드가 있습니다. getResource()라는 메소드는 Resources 라는 클래스의 객체를 리턴합니다. 이 객체는 App이 갖고 있는 자원에 접근할 수 있는 객체입니다. 이 객체를 통해서 AssetManager라는 객체를 얻을 수 있습니다.

Context 클래스
Resources getResource();
리소스 객체를 얻어옵니다.


만약 Activity안에서 AssetManager객체를 얻고자 한다면 다음과 같이 사용할 수 있습니다.

Resources r = getResource();


Context 클래스는 Activity 클래스의 상위 클래스이기 때문에 Activity 안에서는 Context클래스 내의 기능들을 자기것인양 사용할 수 있습니다.

리소스 객체를 얻은 후에는 이 리소스 객체를 통해서 AssetManager 객체를 얻어옵니다.

Resources클래스
AssetManager getAssets();
AssetManager 객체를 얻어옵니다.




AssetManager를 통하여 파일 열기

AssetManager 객체가 생성되면 이 객체의 open() 메소드를 사용하여 InputStream 객체를 얻을 수 있습니다. open() 메소드는 호출 시에 대상 파일의 이름을 문자열로 전달합니다. 파일이 위치한 경로는 이클립스 프로젝트 내의 assets 라는 폴더로 이미 확정이 되어 있는 상태이기 때문에 전달하는 파라미터는 파일의 이름만을 전달합니다. 주의하실 점은 이 메소드를 사용하려면 try { } ~ catch { } 블록으로 묶어 주어야 한다는 점 입니다. 그래서 Asset객체를 통해서 InputStream을 여는 과정은 다음과 같아집니다.

AssetManager am = m_context.getResources().getAssets();  
InputStream is = null;  
  
try {  
    is = am.open("contact.txt");  
    // 스트림을 사용합니다.  
} catch (Exception e) {  
    // 에러가 발생한 경우의 처리  
} finally {  
    if (is != null) {  
        try {  
            is.close();  
            is = null;  
        } catch (Exception e) {}  
    }  
}  
  
am = null;  



test.txt 파일을 읽기

Context객체와 읽어야 할 파일이름을 전달하였을 때, 해당 파일의 내용을 읽어서 문자열로 리턴해 주는 함수를 구현해 본다면 다음과 같이 구현할 수 있겠습니다.

String readAsset(Context context, String file_name) {  
    AssetManager am = context.getResources().getAssets();  
    InputStream is = null;  
    // 읽어들인 문자열이 담길 변수  
    String result = null;  
  
    try {  
        is = am.open(file_name);  
        int size = is.available();  
  
        if (size > 0) {  
            byte[] data = new byte[size];  
            is.read(data);  
            result = new String(data);  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        if (is != null) {  
            try {  
                is.close();  
                is = null;  
            } catch (Exception e) {}  
        }  
    }  
  
    am = null;  
    return result;  
}  

Activity클래스 안에서 사용방법은 다음과 같습니다.

String data = readAsset(this, "test.txt");

 

 

 

반응형

 

 

728x90

 

 

 

 

=================================

=================================

=================================

 

 

출처: http://pgm-progger.blogspot.kr/2011/05/android_27.html

[android] 파일에서 데이터 읽어오기

 

안녕하세요?
프쟁이 입니다.

이 샘플소스는 안드로이드 설치폴더에 android-sdk-windowssamplesandroid-8ApiDemos 위치에 원본소스가 있습니다.

프로젝트의 /assets/ 폴더에는 데이터 파일들을 만들어서, 프로그램에서 이 파일을

스트림 형식으로 읽어들여서, 임의의 처리를 할 수 있습니다.

액티비티의 getAssets() 메소드를 호출하여 애셋매니저 객체를 시스템으로 가져와서,

open 메소드에 파일명을 넘기면, /assets/ 폴더 안에서 해당파일을 InputStream 형식으로

오픈하여, 읽어올 수 있게 됩니다.

원하시는 패키지 경로에 ReadAsset.java 액티비티 클래스 파일을 만듭니다.

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package korsoft.net.Test015;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import korsoft.net.Test015.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;

/**
 * Demonstration of styled text resources.
 * 
 * /assets/ 폴더 안에는 스트림 형식의 파일을 놓고, 프로그램에서
 * 이 파일들을 읽어서 처리를 할 수 있습니다.
 */
public class ReadAsset extends Activity
{
    @Override
 protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // See assets/res/any/layout/styled_text.xml for this
        // view layout definition.
        setContentView(R.layout.read_asset);
        // Programmatically load text from an asset and place it into the
        // text view.  Note that the text we are loading is ASCII, so we
        // need to convert it to UTF-16.
        try {
         /*
          * /assets/read_asset.txt 파일을 열고 있습니다.
          * 시스템에서  getAssets()메소드가 AssetManager 객체를 가져와서,
          * open 메소드에 파일명을 인자로 넘기면, /assets/ 폴더안에서
          * 해당 파일명에 해당하는 파일을 오픈하게 됩니다.
          */
            InputStream is = getAssets().open("read_asset.txt");
            
            // We guarantee that the available method returns the total
            // size of the asset...  of course, this does mean that a single
            // asset can't be more than 2 gigs.
            // 파일 사이즈를 얻습니다.
            int size = is.available();
            
            // Read the entire asset into a local byte buffer.
            // 파일 사이즈만큼 메모리에 데이터를 읽어 들입니다.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            
            // Convert the buffer into a string.
            // 파일로부터 읽어들인 데이터를 텍스트변수에 저장합니다.
            String text = new String(buffer);
            
            // Finally stick the string into the text view.
            // 파일내용을 텍스트 뷰 객체에 출력합니다.
            TextView tv = (TextView)findViewById(R.id.text);
            tv.setText(text);
        } catch (IOException e) {
            // Should never happen!
            throw new RuntimeException(e);
        }
    }
}




/assets/read_asset.txt 파일을 추가해 줍니다.

This text is stored in a raw Asset.
It was read and placed into the TextView here.

액티비티 레이아웃 파일을 /layout/read_asset.xml 추가해줍니다.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<!-- Demonstrates styled string resources.
     See corresponding Java code com.android.sdk.content.StyledText -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView android:id="@+id/text"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textStyle="normal"/>
</LinearLayout>



문자열 리소스를 /values/strings.xml 파일에 설정해 줍니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Test015!</string>
    <string name="app_name">Test015</string>
    
    <string name="activity_read_asset">Content/Assets/Read Asset</string>
    
</resources>



마지막으로 AndroidManifest.xml 파일을 설정해 줍니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="korsoft.net.Test015"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Test015"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ReadAsset" android:label="@string/activity_read_asset">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.SAMPLE_CODE" />
                <category android:name="android.intent.category.EMBED" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://mungi.tistory.com/234

안드로이드 assets 에 관하여 Linux/Android 2011/09/23 14:08

리소스 형식이 아닌 일반 파일에 접근할때는 assets폴더에 화일을 넣고 접근을 하게 되는데..

접근 하는 방식은 다음과 같다.

//assets폴더의  파일을 링크 할때..

//URL로드-- 아래는 로컬 파일 로드
        mWebView.loadUrl("file:///android_asset/img.html");

 

//assets화일에  접근할때

getApplicationContext().getAssets();


AssetManager를 이용한 assets 폴더 접근.



 

 

위 그림 처럼 assets하위에 폴더를 두고 접근을 하고 싶다면 아래와 같이 하면 된다. 

AssetManager am = getResources().getAssets();
InputStream is = am.open("jan/"+(<b>filename</b>));

 

[출처] [android] Assets에 관한 짧은 글|작성자 파란검정



assets 폴더에 있는 파일 전체 sdcard에 복사
 

//퍼미션 중요

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

private void CopyAssets() {
     AssetManager assetManager = getAssets();
     String[] files = null;
     String mkdir = null ;
     try {
         files = assetManager.list("");

        //이미지만 가져올때 files = assetManager.list("image");

     } catch (IOException e) {
         Log.e("tag", e.getMessage());
     }
     for(int i=0; i<files.length; i++) {
         InputStream in = null;
         OutputStream out = null;
         try {
           in = assetManager.open(files[i]);
           
           //폴더생성
           String str = Environment.getExternalStorageState();
           if ( str.equals(Environment.MEDIA_MOUNTED)) {
         mkdir = "/sdcard/elecgal/templet/" ;
         } else {
          Environment.getExternalStorageDirectory();
         }
         File mpath = new File(mkdir);
         if(! mpath.isDirectory()) {
          mpath.mkdirs();
         }
           //
         
           out = new FileOutputStream("/sdcard/elecgal/templet/" + files[i]);
           copyFile(in, out);
           in.close();
           in = null;
           out.flush();
           out.close();
           out = null;
         } catch(Exception e) {
             Log.e("tag", e.getMessage());
         }       
     }
 }
 private void copyFile(InputStream in, OutputStream out) throws IOException {
     byte[] buffer = new byte[1024];
     int read;
     while((read = in.read(buffer)) != -1){
       out.write(buffer, 0, read);
     }

 }

 

=================================

=================================

=================================

 

 

 

반응형


관련글 더보기

댓글 영역