How to get the file extension in Android?

别来无恙 提交于 2020-12-29 05:11:29

问题


I am a newbie. I have an EditText and a Browse Button to explore Folders and select files only. From the Browse Button, when a file is clicked it stores the folder path in which that file is in one string and the file name without extension in other string, which I am using to store, either of these two, in the EditText.

I want to make the file name with the exactly file extension (whether one or two dots), but I don't have any idea how to get the file extension also.

All answers will be appreciated. FileChooser.java

    package com.threefriends.filecrypto;

/**
 * Created by hp on 01-06-2016.
 */

import java.io.File;
import java.sql.Date;
import java.util.ArrayList; 
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent; 
import android.view.View;
import android.widget.ListView; 

public class FileChooser extends ListActivity {

    private File currentDir;
    private FileArrayAdapter adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        currentDir=new File("/sdcard/");
        fill(currentDir); 
    }
    private void fill(File f)
    {
        File[]dirs=f.listFiles();
        this.setTitle("Current Dir: "+f.getName());
        List<Item>dir=new ArrayList<Item>();
        List<Item>fls=new ArrayList<Item>();
        try{
             for(File ff: dirs)
             { 
                Date lastModDate=new Date(ff.lastModified());
                DateFormat formater=DateFormat.getDateTimeInstance();
                String date_modify=formater.format(lastModDate);
                if(ff.isDirectory()){


                    File[] fbuf=ff.listFiles();
                    int buf=0;
                    if(fbuf != null){ 
                        buf=fbuf.length;
                    } 
                    else
                        buf=0;
                    String num_item=String.valueOf(buf);
                    if(buf == 0)
                        num_item=num_item+" item";
                    else
                        num_item = num_item+" items";

                    //String formated = lastModDate.toString();
                    dir.add(new Item(ff.getName(), num_item, date_modify, ff.getAbsolutePath(), "directory_icon"));
                }
                else
                {
                    fls.add(new Item(ff.getName(), ff.length()+" Byte", date_modify, ff.getAbsolutePath(), "file_icon"));
                }
             }
        }catch(Exception e)
        {

        }
        Collections.sort(dir);
        Collections.sort(fls);
        dir.addAll(fls);
        if(!f.getName().equalsIgnoreCase("sdcard"))
            dir.add(0, new Item("..", "Parent Directory", "", f.getParent(), "directory_up"));
        adapter=new FileArrayAdapter(FileChooser.this, R.layout.file_view, dir);
        this.setListAdapter(adapter);
    }
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id){
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        Item o = adapter.getItem(position);
        if(o.getImage().equalsIgnoreCase("directory_icon") || o.getImage().equalsIgnoreCase("directory_up")){
                currentDir=new File(o.getPath());
                fill(currentDir);
        }
        else
        {
            onFileClick(o);
        }
    }
    private void onFileClick(Item o)
    {
        //Toast.makeText(this, "Folder Clicked: "+ currentDir, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.putExtra("GetPath", currentDir.toString());
        intent.putExtra("GetFileName", o.getName());
        setResult(RESULT_OK, intent);
        finish();
    }
}

Part of MainActivity.java

//Defined for file edittext.
    EditText editText2;
 private static String TAG = MainFragment.class.getSimpleName(); //For File Exploring.
    private static final int REQUEST_PATH = 1;
    String curFileName;
    String filePath;
    EditText edittext;
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        edittext = (EditText) view.findViewById(R.id.editText);  //Done for File Exploring, EditText, Browse Button.
        Button b1 = (Button) view.findViewById(R.id.skipButton);
        b1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent1 = new Intent(v.getContext(), FileChooser.class);
                startActivityForResult(intent1, REQUEST_PATH);
            }
        }
        );
}
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // See which child activity is calling us back.
        if (requestCode == REQUEST_PATH)
        {
            if (resultCode == Activity.RESULT_OK)
            {
                curFileName = data.getStringExtra("GetFileName");
                filePath=data.getStringExtra("GetPath");
                edittext.setText(filePath);
            }
        }
    }

回答1:


lots of ways . here are 2 sample-

String someFilepath = "image.fromyesterday.test.jpg"; 
String extension = someFilepath.substring(someFilepath.lastIndexOf("."));

So in you case, it should be something like that

String extension = ff.getAbsolutePath().substring(ff.getAbsolutePath().lastIndexOf("."));

In case if you don't want to do it yourself-

use FilenameUtils.getExtension from Apache Commons IO-

String extension = FilenameUtils.getExtension("/path/to/file/mytext.txt");

or in your case -

String extension = FilenameUtils.getExtension(ff.getAbsolutePath());



回答2:


You could just do it with one line of code using MIME Type Map.

First grab the file:

Uri file = Uri.fromFile(new File(filePath));

Then

String fileExt = MimeTypeMap.getFileExtensionFromUrl(file.toString());



回答3:


You can put your code in your activity like this:

    private String getfileExtension(Uri uri)
        {
            String extension;
            ContentResolver contentResolver = getContentResolver();
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            extension= mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)); 
            return extension;
        }

"uri" is the file uri from the result of "Browse button" selected file




回答4:


Koltin Approach:

val fileExtention: String = file.extension

Check this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/extension.html




回答5:


Function:

public String getExt(String filePath){
        int strLength = filePath.lastIndexOf(".");
        if(strLength > 0)
            return filePath.substring(strLength + 1).toLowerCase();
        return null;
    }

Usage:

String ext = getExt(path);
if(ext != null && ext.equals("txt")){
    // do anything
}

PS: If you don't use toLowerCase(), possible the function returns upper and lower cases (dependent the exists file).



来源:https://stackoverflow.com/questions/37951869/how-to-get-the-file-extension-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!