Question

I had a program work on some images of mine and it returned them to my directory. funny thing, they're now all png images instead of gif.

At first i thought it was simple renaming, but I tested with php using createimagefrompng(), which will throw an error if the image is not a valid png file. No errors were returned.

Wheter or not this gives me a 100% accurate result isn't the issue here, the issue is that I want to rename all those files in a similar way.

Now while I could write a php file to do this for me, I'm wondering how I could do the following in batch or c# or java.

All these files still contain the string ".gif", and I want to remove that. In php it would be as simple as using a foreach-loop, reading the file, using str_replace and then destroying the old one and writing the new one.

I'm kinda stuck as to how I would do this in batch, c# or java, can someone help me here?

Also, I am running windows Vista and I have Powershell 1.0 installed.

Solution 1 - C#:

var files = Directory.GetFiles(@"C:\Downloads\Temp\test\");
foreach (var file in files)
{
  if(file.Contains(".gif"))
  {
    string testing = string.Format("{0}.png", Path.GetFileNameWithoutExtension(file.Replace(".gif", "")));
    File.Move(file, @"C:\Downloads\Temp\test\"+testing);
  }
}
Was it helpful?

Solution

You could probably do something to the extent of the following in c#

var files = new DirectoryInfo(@"c:\files").GetFiles(@"*.gif");
foreach (var file in files)
    File.Move(file.FullName, string.Format("{0}.gif", Path.GetFileNameWithoutExtension(file.FullName)));

or more simply..

var files = Directory.GetFiles(@"c:\files", @"*.gif");
foreach (var file in files)
    File.Move(file, string.Format("{0}.gif", Path.GetFileNameWithoutExtension(file)));

OTHER TIPS

on the command line:

(this assumes that there are no .gif files)

REM first rename all .gif.png to .gif
for %i in (*.gif.png) do ren %i %~ni

REN then rename all .gif to .png
for %i in (*.gif) do ren %~ni.gif %~ni.png

Use for /help to find out what % options your version of Windows supports.

The following with not work with .gif.png, sorry I misread that part.

on the command line (even easier!):

ren *.gif *.png

a Java version (fixed for the .gif.png):

import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main
{
    public static void main(final String[] argv)
    {
        final File   dir;
        final File[] entries;

        dir     = new File(argv[0]);
        entries = dir.listFiles(new FilePatternFilter(".*\\.gif\\.png"));

        for(final File entry : entries)
        {
            if(entry.isFile())
            {
                final String path;
                final String newPath;
                final File   newEntry;

                path     = entry.getPath();
                newPath  = path.substring(0, path.length() - "gif.png".length()) + "png";
                newEntry = new File(newPath);

                if(!(entry.renameTo(newEntry)))
                {
                    System.err.println("could not rename " + entry.getPath() + 
                                       " to " + newEntry.getPath());
                }
            }
        }
    }
}

In Batch you can do the following:

@echo off
setlocal enabledelayedexpansion enableextensions
for %%f in (*.gif.png) do (
    set fn=%%f
    set fn=!fn:.gif=!
    ren "%%f" "!fn!"
)
endlocal

This should work, at least if the files are named .gif.png ... if not, change the filter in the for statement. More help on what you can do with replacements in a set statement are found with help set.

If you want to rename all .png files in a folder to .gif with Java, I'd suggest taking a look at Apache Commons IO. The FileUtils class provides a method for iterating over all files with a given extension ([iterateFiles][3]) while File itself provides a renameTo method.

EDIT: For some reason, stackoverflow doesn't like the usage of paranthesis in link 3, so you'll have to copy and paste it manually. I'd probably go for the batch approach tho, as Java is not exactly your first choice for administrative tasks :)

[3]: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#iterateFiles(java.io.File, java.lang.String[], boolean)

If you can use C, you can use the boost::algorithim stringalgo library and/or boost::regex if you really want a powerful way to do this. Note that using the Windows APIs EDIT( Or linux equivalents) for Move File, etc, will be much faster, because they will simply create new hardlinks on the disk, rather than copying the data over, if such is possible.

For C#, the following will do what you want -
1. Open a DirectoryInfo instance for the directory where the files exist
2. Get all files with the extension you want to change.
3. Change the extension of each file by renaming them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top