org.radonix.moted.service.FileService.java Source code

Java tutorial

Introduction

Here is the source code for org.radonix.moted.service.FileService.java

Source

/*
 * Copyright (C) 2013, Radmon Acaranen.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.radonix.moted.service;

import android.util.Log;

import com.google.common.base.Strings;
import com.google.common.io.Files;

import org.radonix.moted.BuildConfig;
import org.radonix.moted.core.concurrent.Task;
import org.radonix.moted.criteria.SourceEditor;
import org.radonix.moted.util.Const;

import java.io.File;
import java.net.URI;
import java.nio.charset.Charset;

/**
 * Created by Radmon, 2014/12/31 0031.
 */
public class FileService extends Service {

    private static final String TAG = "FileService";

    FileService() {
    }

    public void loadSource(final File file, final SourceEditor editor) {
        executeTask(new Task<String>() {
            @Override
            public String atWorking() throws Exception {
                String source = null;
                if (file.exists() && file.isFile()) {
                    String ext = Files.getFileExtension(file.getName());
                    if (Const.TEXT_FILE_EXTS.contains(ext)) {
                        source = Files.toString(file, Charset.defaultCharset());
                    } else {
                        // File type not supported.
                        // TODO
                    }
                } else {
                    // Cannot find the file.
                    // TODO
                }
                return Strings.nullToEmpty(source);
            }

            @Override
            public void onSuccess(String source) {
                editor.setSource(source);
            }

            @Override
            public void onFailure(Exception e) {
                Log.e(TAG, "Cannot read from " + file.getName(), e);
            }
        });
    }

    public void loadSource(String path, SourceEditor editor) {
        File file = new File(path);
        loadSource(file, editor);
    }

    public void loadSource(URI uri, SourceEditor editor) {
        File file = new File(uri);
        loadSource(file, editor);
    }

}