Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2014 AChep@xda <artemchep@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */

import android.support.annotation.NonNull;

import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    private static final String TAG = "FileUtils";

    public static boolean writeToFileAppend(@NonNull File file, @NonNull CharSequence text) {
        try {
            //noinspection ResultOfMethodCallIgnored
            file.createNewFile();
        } catch (IOException e) {
            Log.w(TAG, "Failed to create the file: file=" + file.getName());
            return false;
        }

        OutputStream os = null;
        InputStream is = null;
        try {
            os = new FileOutputStream(file, true);
            is = new ByteArrayInputStream(text.toString().getBytes("UTF-8"));

            int read;
            final byte[] buffer = new byte[1024];
            do {
                read = is.read(buffer, 0, buffer.length);
                if (read > 0)
                    os.write(buffer, 0, read);
            } while (read > 0);
            return true;
        } catch (Exception e) {
            Log.w(TAG, "Failed to append to a file: file=" + file.getName());
            e.printStackTrace();
        } finally {
            // Try to close the stream.
            if (os != null)
                try {
                    os.close();
                } catch (IOException e) {
                    Log.e(TAG, "Failed to close the stream!");
                    e.printStackTrace();
                }

            // Try to close the stream.
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    Log.e(TAG, "Failed to close the stream!");
                    e.printStackTrace();
                }
        }
        return false;
    }
}