Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static boolean writeToExternalStoragePublic(String filename, String fileContent) {
        boolean saved = false;
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
        if (isExternalStorageAvailable() && !isExternalStorageReadOnly()) {
            try {
                boolean exists = (new File(path)).exists();
                if (!exists) {
                    new File(path).mkdirs();
                }

                //Remote legacy file
                File file = new File(path + filename);
                file.delete();

                // Open output stream
                FileOutputStream fOut = new FileOutputStream(path + filename, true);
                fOut.write(fileContent.getBytes());
                // Close output stream
                fOut.flush();
                fOut.close();

                saved = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return saved;
    }

    public static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    public static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }
}