Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드(Android)에서 프로그래밍 방식으로 디렉토리 생성하기 – 단계별 가이드

이 튜토리얼에서는 안드로이드(Android) 앱에서 프로그래밍 방식으로 디렉토리(폴더)를 생성하는 방법을 단계별로 알아봅니다. 외부 저장소에 새 폴더를 만들고, 그 성공 여부를 토스트(Toast) 메시지로 확인하는 간단한 예제입니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 후 File → New Project 메뉴로 이동합니다. 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하고 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3단계: MainActivity 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 이 코드는 외부 저장소 경로에 “Sample Directory” 폴더가 존재하는지 확인하고, 없으면 mkdirs() 메서드를 호출해 새로 생성한 뒤 그 결과를 토스트 메시지로 알려줍니다.

package com.app.sample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import android.os.Environment;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      File file = new File(Environment.getExternalStorageDirectory()+"/Sample Directory");
      boolean success = true;

      if(!file.exists()) {
         Toast.makeText(getApplicationContext(),"디렉토리가 존재하지 않아 새로 생성합니다",Toast.LENGTH_LONG).show();
         success = file.mkdirs();
      }

      if(success) {
         Toast.makeText(getApplication(),"디렉토리가 생성되었습니다",Toast.LENGTH_LONG).show();
      }
      else {
         Toast.makeText(this,"디렉토리 생성에 실패했습니다",Toast.LENGTH_LONG).show();
      }
   }
}

4단계: 매니페스트에 권한 추가

외부 저장소에 폴더를 생성하려면 쓰기 권한이 반드시 필요합니다. Manifests/AndroidManifest.xml 파일에 아래와 같이 WRITE_EXTERNAL_STORAGE 권한을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.app.sample">

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

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

참고: Android 6.0(API 23) 이상에서는 매니페스트에 권한을 선언하는 것만으로는 부족하며, 앱 실행 중 사용자에게 런타임 권한을 직접 요청해야 합니다. 또한 Android 10(API 29)부터는 스코프 스토리지(Scoped Storage) 정책이 적용되므로, 상황에 따라 requestLegacyExternalStorage 속성 활용이나 MediaStore API 사용도 함께 검토하는 것이 좋습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run 안드로이드(Android)에서 프로그래밍 방식으로 디렉토리 생성하기 – 단계별 가이드 아이콘을 클릭합니다. 실행 대상으로 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드(Android)에서 프로그래밍 방식으로 디렉토리 생성하기 – 단계별 가이드