Android/StoreInfo

다양한 경로에 접근하여 파일 생성 및 수정

re트 2024. 10. 2. 11:28
728x90
public class MainActivity extends AppCompatActivity {
    private static final int CREATE_FILE = 1;

    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        String fileName = "sample2.txt";

        Button btnString1 = findViewById(R.id.btn_string1);
        btnString1.setOnClickListener(view -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                File[] files = new File[]{
                        new File(getDataDir(), fileName),
                        new File(getFilesDir(), fileName),
                        new File(getCacheDir(), fileName),
                        new File(getCodeCacheDir(), fileName),
                        new File(getExternalFilesDir(null), fileName),
                        new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), fileName),
                        new File(getExternalCacheDir(), fileName),
                        new File(getObbDir(), fileName),
                        new File(getNoBackupFilesDir(), fileName),
                        new File(Environment.getDownloadCacheDirectory(), fileName),
                        new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), fileName),
                        new File(Environment.getDataDirectory(), fileName),
                        new File(Environment.getDataDirectory(), fileName),
                        new File(Environment.getExternalStorageDirectory(), fileName),
                        new File(getApplicationInfo().dataDir, "shared_prefs/test.xml")
                };

                for (File file : files) {
                    Log.d("ABOUT_FILE", file.toString());
                }

                for (File file : files) {
                    try {
                        if (file.createNewFile()) {
                            Log.d("ABOUT_FILE", "SUCCESS_CREATE_NEW_FILE " + file);
                        } else {
                            Log.d("ABOUT_FILE", "FAILURE_CREATE_NEW_FILE " + file);
                        }
                    } catch (IOException e) {
                        Log.d("ABOUT_FILE", e.getMessage());
                    }
                }
            }
        });

        Button btnString2 = findViewById(R.id.btn_string2);
        btnString2.setOnClickListener(view -> {
            File file = new File(Environment.getDataDirectory(), fileName);
            if (file != null) {
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    Log.d("ABOUT_FILE", "SUCCESS_ACCESS_FILE");
                } catch (IOException e) {
                    Log.d("ABOUT_FILE", e.getMessage());
                }
            }
        });

        Button btnString3 = findViewById(R.id.btn_string3);
        btnString3.setOnClickListener(view -> {
            File[] files = new File[]{
                    new File(getDataDir(), fileName),
                    new File(getFilesDir(), fileName),
                    new File(getCacheDir(), fileName),
                    new File(getCodeCacheDir(), fileName),
                    new File(getExternalFilesDir(null), fileName),
                    new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), fileName),
                    new File(getExternalCacheDir(), fileName),
                    new File(getObbDir(), fileName),
                    new File(getNoBackupFilesDir(), fileName),
                    new File(Environment.getDownloadCacheDirectory(), fileName),
                    new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), fileName),
                    new File(Environment.getDataDirectory(), fileName),
                    new File(Environment.getDataDirectory(), fileName),
                    new File(Environment.getExternalStorageDirectory(), fileName),

            };

            for (File file : files) {
                try (FileOutputStream fos = new FileOutputStream(file, true)) {
                    fos.write("add content\n".getBytes());
                    Log.d("ABOUT_FILE", "SUCCESS_MODIFY_FILE" + file);
                } catch (IOException e) {
                    Log.d("ABOUT_FILE", e.getMessage());
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createFile() {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TITLE, "sample.txt");

        startActivityForResult(intent, CREATE_FILE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CREATE_FILE && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            assert uri != null;
            Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show();
        }
    }
}
반응형

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

동적 브로드캐스트 리시버 구성  (0) 2024.10.02
<정리> Permission  (0) 2024.09.22
<정리> Data and file storage  (1) 2024.09.21
onBackPressedCallback()  (0) 2024.07.03
<정리> 안드로이드 플랫폼  (1) 2024.07.02