48

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);
            }
        }
    }
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
Bati
  • 529
  • 3
  • 6
  • 15
  • Please show the code where you "explore Folders and select files only". – CommonsWare Jun 21 '16 at 18:26
  • Yes, I have editted it. There are some more files for File Explorer, those are for logic, these two I have editted, are the main files. Tell if those also needed. File's parent path is storing in filePath and File name storing in curFileName. – Bati Jun 21 '16 at 18:33
  • http://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java – CommonsWare Jun 21 '16 at 18:44

11 Answers11

90

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());
Amit K. Saha
  • 5,871
  • 2
  • 27
  • 35
32

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());
Acheme Paul
  • 1,194
  • 15
  • 19
17

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

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
niceumang
  • 1,347
  • 1
  • 8
  • 21
6

Kotlin Approach:

val fileExtention: String = file.extension

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

mad_lad
  • 654
  • 3
  • 8
  • 20
4

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).

Eugen
  • 1,356
  • 12
  • 15
4

In Kotlin

You can read the MimeTypeMap documentation here

This is example if you are using startActivityForResult and you get data from it. Then you define Content Resolver to get mime type from the uri.

val uri: Uri? = it.data?.data
val contentResolver = requireContext().contentResolver
val stringMimeType = contentResolver.getType(uri!!)

Using that code, if you choose pdf file you will get something like

"application/pdf"

After that, using the MimeTypeMap you'll get the extensions. Don't forget that you should add getSingleton() because it's only available in singleton.

val stringFileType = MimeTypeMap.getSingleton().getExtensionFromMimeType(stringMimeType)
Fuad Reza
  • 161
  • 2
  • 6
2

I used DocumentFile to get the file name and extension

DocumentFile documentFile = DocumentFile.fromSingleUri(YourActivity.this, fileUri);

String fileName = documentFile.getName();
String extension = fileName.substring(fileName.lastIndexOf("."));

For example, if your file name is 'your_image.jpg' then the extension will be '.jpg'

1

In Java

public String getFileExt(String fileName) {
    return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
  }

In Kotlin

 fun getFileExt(fileName: String): String? {
    return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)
  }
Fakhar
  • 3,946
  • 39
  • 35
0

Kotlin

import android.webkit.MimeTypeMap    

MimeTypeMap.getFileExtensionFromUrl("my.xlsx") // xlsx
MimeTypeMap.getFileExtensionFromUrl("my.pdf") // pdf
MimeTypeMap.getFileExtensionFromUrl("http://www.google.com/my.docx") // docx
MimeTypeMap.getFileExtensionFromUrl(File.createTempFile("aaa", ".txt").absolutePath) // txt
Hun
  • 3,652
  • 35
  • 72
0

Getting extension of file in Kotlin:

 fun getExtension(fileName: String): String {
                return fileName.substring(if (fileName.lastIndexOf(".") > 0) fileName
                    .lastIndexOf(".") + 1 else return "",fileName.length)
            }
  • In kotlin, one can use `File.extension` to get the extension of the file, no need of writing this. Read more here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/extension.html – Abhishek Dutt Jul 07 '22 at 08:04
0
getContentResolver().getType(theReceivedUri); // return  "media/format"
Falchio
  • 174
  • 1
  • 14