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!

file io question(s)

Status
Not open for further replies.

GiffordS

Programmer
May 31, 2001
194
CA
Ok, you have to consider me a total Java novice. I knew enough to write a few applets, but that was years ago. Now I've decided to tackle a few projects in cleaning up my pc and am trying to use Java, but have found that what I do know is rusty and even if it weren't it isn't enough.

The problem I'm having is that I have tons of pics in various directories that I want to rename, or append the year 2005 to the names of them. For example, I have a folder, Pics, that contains several subfolders. One is named Holidays. In the Holidays folder is about 300 images that I would like to just add "---2005" to the end of so that "laborday014.jpg" would become "laborday014---2005.jpg". You get the idea. Having written only applets in the past I am totally lost for how to navigate and work with files on my hard drive. So here's what I know right now....

I'm going to need to import java.io.* and java.util.*. Thanks to a different thread here already I know that I can do something like this to read the filenames into an array...

File file = new File(c:\Pics\Holidays);
String[] list = file.list();

As I understood the other thread this should read all 342 or whatever pics in the Holidays folder into the array named list.

From there I believe that I can then sort the array by name using..

sort(list);

This should then sort the array into alphabetical order, which is not necessary for this folder but could be in other folders if I want to append increasing numbers to files such as "auntpolly---001.jpg", "auntpolly---002.jpg", etc. Either way I need the experience working with arrays so I'm just checking that I am using the sort() function correctly.

Ok, from there I can set up a for loop to iterate through the array and rename each file as it goes. Something like this...?

for(int 1=0; 1<list.length; i++)
{current=file.this;
String newName=current+"---2005";
renameTo(newName);}

This is where I start to seriously doubt myself. It seems like something is missing, but I've kicked through a few reference books and it's not readily apparent. My first concern is that when I am reading the file names into the array, am I also reading the extension? If so, then am I not renaming "laborday014.jpg" to "laborday014.jpg---2005"? That would not be a good thing at all. So question one is.. am I just picking up the file names or am I picking up the extensions as well? The second question has to do with the renameTo() function. What am I renaming? Will this rename the actual file or just rename the value in the array? I know this must seem like I know just enough to be dangerous, but I would appreciate any help I can get here.
 
Some considerations:

1.- I'd consider doing it with command line
2.- You're getting the full name. Java tends to be cross-platform, and in some OSs extensions make no difference at all.
3.- You're renaming the phisycal file.

Cheers,
Dian
 
I'm not sure what you mean by doing it w/ command line. If you mean going file by file and manually changing the names, I probably have a few thousand pictures from various vacations and whatnot on that machine, so I'd really rather not change them one at a time.

As for your other comments, are you saying that I'm not terribly far off the mark? It sounds as if all I need to do is manipulate the string to first drop the ".ext" and then append "---2005.ext". Is that correct? Easy enough in PHP, but most variables are easier to work with in PHP. If that's all I'm looking at to make it work then I'll need to refresh myself on String manipulation in Java.
 
This loop is totally broken:
Code:
 for(int 1=0; 1<list.length; i++)
{current=file.this;
String newName=current+"---2005";
renameTo(newName);}
a) you can't assign another value to 1.
Use i instead. (At the comparision to list.length too).
b) file.this is bogus.
Use list instead.
c) list is an array of String, not of file.
And therefore it contains just names.
The javadocs tell you what a method returns.

String newfile = list.substring (0, list.length () - 4);
newfile = newfile + "---2005.jpg";

Are you sure no 'jpeg' - suffix is used?
To call 'renameTo', you first need a FileObject.

If you use listFiles () instead of list (), you get an Array of Files, which will be much more usable for you.

And you may not call 'sort (list)' without writing a local Method 'sort'.
You may call Arrays.sort (list);



seeking a job as java-programmer in Berlin:
 
Thank you stefan, very much there that was helpful. The 1 was supposed to be an i all along, those are just typos. Your points about the sort() method made sense as soon as I saw them. You do bring up some interesting things that unfortunately leave me with more questions...

You said..

"If you use listFiles () instead of list (), you get an Array of Files, which will be much more usable for you."

This makes sense, but I'm not sure where you mean I should use listFiles() as opposed to list(). Are you saying that I shouldn't declare the array as a String array at all? I'm a little confused. Instead of..

String[] list = file.list();

Should I be using ...

File[] list=listFiles(c:\Pics\Holidays);

I'm not sure if that's what you meant. But if it is, and I then have an array of files, wouldn't I be able to use list to create the file object that can be renamed with renameTo()?

File namedFile=list;
namedFile.renameTo(newfile);

Or am I just fishing at this point.
 
Upon further review....

I've really made a hash of this and I think that some of the advice here may have been a little off as well. I can generate the file array, but then I can't use the value of list as a String. And even if I do, I cannot then use a string in the renameTo() method. They all throw exceptions. I either need to use files throughout or strings throughout, and I'm really not sure which is correct. Everything I've read says that renameTo() requires a file as the destination, so the compiler exception makes sense in that regard. But how on earth do I manipulate the file name? There is no substring() method for files.
 
Sorry... just realized that my last post is a little vague without showing the code.

Code:
import java.io.*;
import java.util.*;

class renfile
{public static void main(String[] args)
     { File dir = new File("C\\ren\\");
       File[] list = dir.listFiles();
     for(int i=0;i<list.length;i++)
     {  File current=list[i];
        int ep=current.length();
       int nep=ep-4;
      String newfile = current.substring (0, nep);
newfile = newfile + "---2005.jpg";
File namedFile=list[i];
namedFile.renameTo(newfile);}}}

The compiler errors that I am getting are for...

File current=list; Possible loss of precision error

String newfile = current.substring (0, nep); Cannot find symbol (whatever that means)

namedFile.renameTo(newfile); renameTo(java.io.File) in java.io.File cannot be applied to (java.lang.String) which is the datatype problem I mentioned earlier.

Any help would be appreciated.
 
Whats up with that funky bracket style ? Not very easy to read. Consider this code - its kind of like what you are doing, but a little better :
Code:
 import java.io.*; import java.util.*;  public class RenameFile {  public static void main(String[] args) {    if (args.length != 1) {    System.out.println("Usuage : java RenameFile <dir_name>");    System.exit(0);   }    File dir = new File(args[0]);     File[] list = dir.listFiles();   for(int i = 0; i< list.length; i++) {      String[] dottedFileNameParts = list[i].toString().split("\\.");    if (dottedFileNameParts.length > 0) {     String renameToName = "";     for (int j = 0; j < dottedFileNameParts.length -1; j++) {      renameToName += dottedFileNameParts[j] +".";     }        renameToName += "---2005." +dottedFileNameParts[dottedFileNameParts.length -1];            System.out.println("Renaming " +list[i].toString() + " to " +renameToName);      list[i].renameTo(new File(renameToName));     } else {     System.out.println("Odd file name or directory : " +list[i].toString());    }     }  } }

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Reading the javadocs (and perhaps some tutorials) should be your first source of information.

current.length(); returns the length of the file, not the length of its name.
Code:
 for (int i=0; i<list.length; i++)
	{ 
		File current=list [i];
		Sting fname = current.getName ();
		int suffixPosition = fname.length - 4;
		String newfile = current.substring (0, sufixPosition);
		newfile = newfile + "---2005.jpg";
		list [i].rename_to (new File (newfile));
	}
Since you're somewhat relaxed about typos, I put 3 typos into my code.

seeking a job as java-programmer in Berlin:
 
I'm a complete novice, myself, but I wrote a similar application to get the files off my camera and name them something more useful. In my case, I point to a directory and rename all the files with some extention (default is .jpg) to a prefix then "-xxx", where xxx increments. If I default the prefix, the program uses YYddd (where ddd is day of year). Here it is, if you'd like to scavenge it. No claims here that it's particularly good code:
Code:
//------------------------------------imports
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
//
class jpgRnm extends Frame implements ActionListener {
//------------------------------------class data
FileDialog fd1;
TextField sdir, pfix, ext;
String suffix;
//----------------------------------main method
	public static void main(String args[]) {
		jpgRnm jpgRnm1 = new jpgRnm();
	     //-----------------------Initilaize
	}
//---------------------------------constructor method
      public jpgRnm() {
		setTitle("Picture Names");
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
          ScrollPane sp = new ScrollPane();
          Panel p0 = new Panel();
          p0.setLayout(new GridLayout(0,1));
		Panel p1 = new Panel();
		p1.setLayout(new GridLayout(0,1));
          p0.add(p1);
          Label l1 = new Label("Source");
          p1.add(l1);
          sdir = new TextField("C:\\My Documents\\temp\\");
          ext = new TextField(".jpg");
          p1.add(sdir);
          p1.add(ext);
          Label l2 = new Label("Prefix (if none: yyddd)");
          p1.add(l2);
          pfix = new TextField();
          p1.add(pfix);
		//---------------------------menu
		MenuBar mb1=new MenuBar();
		this.setMenuBar(mb1);
		Menu m1=new Menu("File");
		MenuItem f11=new MenuItem("Source");
		f11.addActionListener(this);
		MenuItem f13=new MenuItem("Quit");
		f13.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		m1.add(f11);
		m1.add(f13);
		Menu m2 = new Menu("Actions");
		MenuItem f21 = new MenuItem("Rename");
		f21.addActionListener(this);
		MenuItem f24 = new MenuItem("");
		f24.addActionListener(this);
		m2.add(f21);
		mb1.add(m1);
		mb1.add(m2);
          //
          sp.add(p0);
          sp.setSize(280,150);
          add("Center", sp);
 		pack();
		show();
      }
//-------------------------------------event handler
	public void actionPerformed(ActionEvent e) {
		Object esrc = e.getSource();
		if (esrc instanceof MenuItem && e.getActionCommand()=="Source") {
			fd1=new FileDialog(this,"Open File",FileDialog.LOAD);
			fd1.show();
			sdir.setText(fd1.getDirectory());
          }
		else if (esrc instanceof MenuItem && e.getActionCommand()=="Rename") {
               String srcFile = sdir.getText();
               String prefix = pfix.getText();
               suffix = ext.getText();
               File in = new File(srcFile);
               FilenameFilter pixFilt = new FilenameFilter() {
                          public boolean accept(File in, String name) {
                            return name.endsWith(suffix);
                          }
               };
               File jpegs[] = in.listFiles(pixFilt);
               int numpx = jpegs.length;
               Calendar filedate =Calendar.getInstance();
               int yfld = filedate.YEAR;
               int dfld = filedate.DAY_OF_YEAR;
               for (int i = 0; i<numpx; i++) {
                   filedate.setTime(new Date(jpegs[i].lastModified()));
                   String trgFile = String.valueOf(filedate.get(yfld));
                   trgFile = trgFile.substring(2)+String.valueOf(filedate.get(dfld));
                   if (prefix.length()>0) {trgFile=prefix;  }
                   trgFile = trgFile+"-"+(i+1)+suffix;
                   File out =  new File(srcFile+trgFile);
                   jpegs[i].renameTo(out);
               }
		}

	}
}

_________________
Bob Rashkin
 
Thank you all very much for your help. I'm not quite sure why it makes people feel better about themselves to take shots at someone as they ask for help, but if it's what you need that's cool. For what it's worth, I didn't realize my brackets were "funky". I know it's not the exact bracket style you learn in Java101, but I've worked a lot in other languages such as PHP where brackets are not as ubiquitous and it's just a style I've developed over time. As for the typo thing, I never said that I was relaxed about them. I mentioned that the two errors in that one line of code were typos not to minimize my mistakes but to hopefully give someone who was helping me a better sense of what I did and did not understand. I said all along that I was pretty lost so I don't think my ego got in the way here. So I do sincerely appreciate the help, and yes, I will continue to review the docs and other materials as I wade back into Java.
 
Well - if you post errornous code to a forum, you should allways use the real code which is producing the error.

How shall we know what's a typo and what's the real problem?

Reducing the code to a bare minimum is a good idea, but the reduced code should be checked by you.

Since it is you who is asking for help, it should be self-evident, that you do as much work on your own as possible, including reviewing your own post, and using a somewhat consistent and readable coding-style.

Nobody is asking to stick for an official style.

And I would feel better if you or someone else reading this would understand why the form of asking is necessary.

When I like to be cool, I just ignore malformed posts.

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top