Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Renaming all files in a directory. 1

Status
Not open for further replies.

kodr

Programmer
Dec 4, 2003
368
0
0
I'm stuck and can't quite figure out what I'm doing wrong.

I'm trying to change the extensions of every file in a selected directory.

Here's what I've got:

Code:
import java.awt.*;
import java.awt.event.*;	// ActionListener
import javax.swing.*;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileRenamer2 extends JFrame
{
	JPanel main = new JPanel(new BorderLayout() );
	JPanel scPane = new JPanel( new GridLayout( 1, 2, 5, 5 ) );
	JPanel btnPane = new JPanel( new FlowLayout() );

	JButton btn;
	String face = "Open File";

	private JTextArea outputArea, outputArea2;
	private JScrollPane scrollPane, scrollPane2;

	// main method
	public static void main( String args[] )
	{
		new FileRenamer2();
	}

	// set-up GUI
	public FileRenamer2()
	{
		super("TestApp");
		setBounds(100,100,800,800);
    	setDefaultCloseOperation(EXIT_ON_CLOSE);
		Handler handler = new Handler();	// Create bhandler (button handler)

		outputArea = new JTextArea();
		scrollPane = new JScrollPane( outputArea );

		outputArea2 = new JTextArea();
		scrollPane2 = new JScrollPane( outputArea2 );

		scPane.add( scrollPane );
		scPane.add( scrollPane2 );

		btn = new JButton( face );
		btnPane.add( btn );
		btn.addActionListener( handler );

		main.add( "Center", scPane );
		main.add( "South", btnPane );

		this.getContentPane().add( main );
		setVisible( true );
		this.setResizable( false );
	}// end HW5

	// display file dialog
	private File getFile()
	{
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
		int result = fileChooser.showOpenDialog( this );
		if ( result == JFileChooser.CANCEL_OPTION )
			System.exit( 1 );
		File fileName = fileChooser.getSelectedFile();
		if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
		{
			JOptionPane.showMessageDialog( this, "Invalid File Name", "Invalid File Name",
				JOptionPane.ERROR_MESSAGE );
			System.exit( 1 );
		}
		return fileName;
	}// end getFile

	// open file and display contents in a JTextArea
	private void processFile( File name )
	{
		String directory[] = name.list();
		for ( String directoryName : directory )
		{
			String fName = directoryName;
			String newfName = changeExtension( fName, ".test" );

			File oldFile = new File(fName);
			File newFile = new File( newfName );
			outputArea.append( directoryName + "\n" );
			oldFile.renameTo( newFile );
			outputArea2.append( newfName + "\n" );
		}

	}// end processFile


	// Handler - determines what button was pressed
	private class Handler implements ActionListener
	{
		public void actionPerformed(ActionEvent ev)
		{
			if ( ev.getSource() == btn )
			{
				processFile( getFile() );
			}

		}// end actionPerformed
	}// end handler

//============================================== changeExtension
    // changes extension to new extension
    // example: x = changeExtension("data.txt", ".java")
    //         will assign "data.java" to x.
	private String changeExtension(String originalName, String newExtension)
	{
    	int lastDot = originalName.lastIndexOf(".");
    	if (lastDot != -1)
    	{
        	return originalName.substring(0, lastDot) + newExtension;
    	}
    	else
    	{
        return originalName + newExtension;
    	}
	}//end changeExtension


}

What's happening is, when I select a folder, everything looks like it ran okay, but the files don't change. I've tried testing for the newfName, and seen it's been changed correctly. Any ideas? Thanks.
 
Everything looks ok, because you don't look at all:
Code:
 private void processFile (File name)
	{
		String directory [] = name.list ();
		for (String directoryName : directory)
		{
			String fName = directoryName;
			String newfName = changeExtension (fName, ".test");
			File oldFile = new File (fName);
			File newFile = new File (newfName);
			outputArea.append (directoryName + "\n");
			boolean ok = oldFile.renameTo (newFile);
			if (ok) outputArea2.append (newfName + "\t" + ok + "\n");
			else outputArea2.append ("failed: " + newfName + "\n");
		}
	}

don't visit my homepage:
 
Thanks for the reply. Actually I had almost the same code in there before, but I've re-written that method so many times trying to get it to work that I left it out of the version I posted.

Any idea why I'm not able to rename the files in the directory that I choose? I created a folder called "Test Folder" in my root directory, and created three blank text files (1.txt , 2.txt, 3.txt ).

I did find that if I hard coded a file name "c:\\test.txt" I could rename it, but for some reason I can't get .renameTo to work with a file name coming from the chooser portion of my code.
 
From javadocs, File:

list()
... Each string is a file name rather than a complete path.

So running your program in /home/kodr you choose a directory /home/kodr/test/ with a file foo.txt, the program will try to rename a file /home/kodr/foo.txt to whatsoever.

don't visit my homepage:
 
Thanks.

Here's what I ended up with:

Code:
private void processFile (File name)
    {
        String directory [] = name.list ();
        String path = name.getAbsolutePath();
        for (String directoryName : directory)
        {
            String fName = directoryName;
            String newfName = changeExtension (fName, ".test");
            File oldFile = new File ( path + "\\" + fName);
            File newFile = new File ( path + "\\" + newfName);
            outputArea.append (directoryName + "\n");
            boolean ok = oldFile.renameTo (newFile);
            if (ok) outputArea2.append (newfName + "\t" + ok + "\n");
            else outputArea2.append ("failed: " + newfName + "\n");
        }
    }

I had to add the path to both the original and new name, and that got everything working.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top