Java tutorial
//package com.java2s; /* * Copyright (C) 2007-2008 OpenIntents.org * * 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. */ import java.io.File; import java.net.URISyntaxException; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; public class Main { /** TAG for log messages. */ static final String TAG = "FileUtils"; private static final boolean DEBUG = false; /** * Convert Uri into File. * @param uri * @return file */ public static File getFile(Uri uri) { if (uri != null) { String filepath = uri.getPath(); if (filepath != null) { return new File(filepath); } } return null; } /** * Constructs a file from a path and file name. * * @param curdir * @param file * @return */ public static File getFile(String curdir, String file) { String separator = "/"; if (curdir.endsWith("/")) { separator = ""; } File clickedFile = new File(curdir + separator + file); return clickedFile; } public static File getFile(File curdir, String file) { return getFile(curdir.getAbsolutePath(), file); } /** * Get a file path from a Uri. * * @param context * @param uri * @return * @throws URISyntaxException * * @author paulburke */ public static String getPath(Context context, Uri uri) throws URISyntaxException { if (DEBUG) Log.d(TAG + " File -", "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: " + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme() + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString()); if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = { "_data" }; Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow("_data"); if (cursor.moveToFirst()) { return cursor.getString(column_index); } } catch (Exception e) { // Eat it } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } }