Monday, October 7, 2013

parsing filename into parts

This is an example of String manipulation using Android/Java. The code uses a subroutine to do the work, and is explained below. First the complete code:




package com.wpd0101.parseFileName;

import android.app.*;
import android.os.*;
import android.util.*;

public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
//http://android-er.blogspot.com/2011/04/how-to-get-file-extension-using-java.html?m=1
private static final String TAG = "DEBUG-parseFileName";
    @Override
    public void onCreate(Bundle savedInstanceState)
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

String infile = "jack.jpg";
String first = myFileName(infile);
Log.v(TAG," result = "+first);
    }
In above code, the call to the subroutine returns a value (String) of "first". Presumably, one would do something with this value elsewhere in one's programming.

public String myFileName(String infile){
Log.e("arg was ",infile);
int dotposition= infile.lastIndexOf(".");
Log.v("dotpos = ",String.valueOf(dotposition));
return(infile.substring(0,dotposition));
//ext = file.substring(dotposition + 1, file.length());
}
}
The second part of the code takes this incoming complete filename, locates the position of the "dot", and returns the string of characters leading up to but not including the "dot" itself. If one needed the extension, one could define a String called "ext" in this example, and remove the "//" from the code to pass that value back.

No comments:

Post a Comment