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.util.ArrayList;
import java.util.StringTokenizer;

public class Main {
    /**
     * Change the extension of specified file.<br>
     * Usage :<br>
     * f.renameTo(MyFileUtility.reExtension(f, "jpg")) ;<br>
     * As we know ,File class is a dummy File , <br>
     * thus , you must follow the usage to change extension.
     * @param fin File input
     * @param newExtension newExtension without '.'
     * @return File with new extension
     */
    public static File reExtension(File fin, String newExtension) {
        //Usage: f.renameTo(MyFileUtility.reExtension(f, "jpg")) ;
        StringTokenizer strTokener = new StringTokenizer(fin.getName(), ".");
        //For a file may has many '.' in its file name , we use a collection to stroe it.
        ArrayList<String> strVec = new ArrayList<String>();
        while (strTokener.hasMoreTokens())
            strVec.add(strTokener.nextToken());

        String newName = "";
        //Give up the original extension
        for (int i = 0; i != strVec.size() - 1; ++i) {
            newName += strVec.get(i);
            newName += ".";
        }
        newName += newExtension;
        return new File(fin.getParent() + "\\" + newName);
    }
}