views:

558

answers:

6

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);
  }
}
A: 

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.

Mohit Chakraborty
+3  A: 

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.

Joey
When executing this from the correct directory, dos tells me this: The syntax of the command is incorrect.
WebDevHobo
It worked fine for me here. You have to put it into a batch file, though. Simply typing the commands on the commandline won't work.
Joey
+1  A: 

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)

springify
I unsucessfully tried to fix the link in the parens I added a uservoice item for it http://stackoverflow.uservoice.com/pages/general/suggestions/146461-markdown-link-in-parens-text-1-
Unkwntech
+4  A: 

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());
                }
            }
        }
    }
}
TofuBeer
+1 for ren *.gif *.png. So many people don't realize that's possible!
Jim Mischel
hmz, what is this %~ni variable? If cannot find it when typing "for /?" into the DOSbox
WebDevHobo
also, the batch command has no effect. Nothing happens. I executed it from the directory where the files are located. Also, I don't know that much about batch, but from looking at your code, seems like "fileName.gif" into "fileName.gif.png", and I'm looking for "fileName.gif.png" to "fileName.png"
WebDevHobo
What version of Windows are you on? Whoops on the .gif.png... I'll update it (bad reading day :-)
TofuBeer
I'm on windows Vista. I should probably mention I have powershell installed as well...
WebDevHobo
the %~ni works on Vista (not sure about in powershell, I don't have it installed)
TofuBeer
+1  A: 

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)));
Quintin Robinson
var files = Directory.GetFiles(@"c:\files", @"*.gif"); works just as well w/o creating a DirectoryInfo instance.
Lucas
actually, all the filles are currently like this: "filename.gif.png".And I want to change them to "filename.png". But with your hint, I think I'll be able to do it.
WebDevHobo
Actually, something can go wrong here. The File.Move() function requires the new path to be absolute. So just adding "filename.png" as the new location will throw and IOException, at least that's what Visual Studio did for me during debugging
WebDevHobo
Yeah sometimes i'm terrible when not actually writing in an IDE, you would have to specify the filter as *.png lol. File.Move will work with a relative path but only the current working directory so you would have to concatenate the directory and filename. Glad you got something working though!
Quintin Robinson
A: 

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.

Billy ONeal