Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.os.Environment;

public class Main {
    public static File storeToFile(Context context, InputStream is) throws IOException {
        if (is == null) {
            return null;
        }
        OutputStream os = null;
        File f = null;
        try {
            File outputDir = getSDPath(context);
            f = File.createTempFile("qiniu-", "", outputDir);
            os = new FileOutputStream(f);
            byte[] buffer = new byte[64 * 1024];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            if (f != null) {
                f.delete();
                f = null;
            }
            throw e;
        } finally {
            try {
                is.close();
            } catch (Exception e) {
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }

        return f;
    }

    public static File getSDPath(Context context) {
        File sdDir = context.getCacheDir();
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        return sdDir;
    }
}