Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;

import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.File;

import java.io.FileWriter;
import java.io.IOException;

public class Main {
    private static final String DIR_BOARDS_EXTERNAL = "GameOfLife";

    public static void saveBoardToExternal(Context context, String fileName, JSONObject jsonObject) {
        File file = new File(getDirectoryBoards(), fileName);
        if (file.exists()) {
            file.delete();
        }

        try {
            file.createNewFile();
            BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
            buf.append(jsonObject.toString());
            buf.close();
            addTomMediaScanner(context, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static File getDirectoryBoards() {
        File file = new File(Environment.getExternalStorageDirectory(), DIR_BOARDS_EXTERNAL);
        if (!file.exists()) {
            file.mkdir();
        }

        return file;
    }

    private static void addTomMediaScanner(Context context, File file) {
        addTomMediaScanner(context, Uri.fromFile(file));
    }

    private static void addTomMediaScanner(Context context, Uri uri) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(uri);
        context.sendBroadcast(mediaScanIntent);
    }
}