create File With Name - Android File Input Output

Android examples for File Input Output:File Name

Description

create File With Name

Demo Code


//package com.java2s;

import android.os.Environment;
import android.util.Log;
import java.io.File;

import java.io.IOException;

public class Main {
    private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
    private static final String AUDIO_RECORDER_STORAGE_FOLDER = Environment
            .getExternalStorageDirectory() + "/" + AUDIO_RECORDER_FOLDER;

    public static String createFileWithName(String filename) {
        // check and create if not exist folder for saving files
        File folder = new File(AUDIO_RECORDER_STORAGE_FOLDER);
        if (!folder.exists()) {
            folder.mkdirs();//ww w . j ava2  s . c o  m
        }

        String filePath = String.format("%s/%s", AUDIO_RECORDER_FOLDER,
                filename);
        String fullFileStoragePath = getFileStoragePath(filePath);
        File file = new File(fullFileStoragePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
                Log.i("lanna", "created file for saving at " + file);
                return filePath;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Log.i("lanna", "fail to create file for saving at " + file);
        return null;
    }

    public static String getFileStoragePath(String filePath) {
        return String.format("%s/%s",
                Environment.getExternalStorageDirectory(), filePath);
    }
}

Related Tutorials