-5

I have file names like 323423233.

I want to add the last 2 digits of the file name and add it to the front and make it 33/323423233 and add extension to it(like .doc).

What's a simple statement that I can use to achieve this?

  • 3
    Are you sure you want to have a slash in the file name? :) – summea Jun 12 '13 at 20:54
  • Which File System supports `/` in the filename? Anyway, look at the `java.io.File` class. – SJuan76 Jun 12 '13 at 20:54
  • 1
    Does it have to be java? Shell scripting is more suited for this type of task. – Santa Jun 12 '13 at 20:54
  • 1
    Could you paste the code whatever you tried? – sattu Jun 12 '13 at 20:54
  • @SJuan76 NOT! This is 2013, use `Files` and `Path` – fge Jun 12 '13 at 20:55
  • What system are you on and what tools are you using? It must be pretty strange to support a '/' in the filename - I can't guess what platform you are talking about. – D Mac Jun 12 '13 at 20:55
  • Yea it has to be java. It's the requirement to put /. – user2476268 Jun 12 '13 at 20:55
  • 5
    @DMac - He probably wants to create directories as well. Obviously the OP has done a poor job of specifying his requirements (as well as researching how to implement them). – jahroy Jun 12 '13 at 20:56
  • 2
    Guess: OP wants to _create directory `33`_ and put the file under that directory – fge Jun 12 '13 at 20:56
  • 1
    "It's going inside database so / has to be used" <-- eh? Sorry, but I fail to see the relationship here – fge Jun 12 '13 at 20:57
  • 1
    Do you actually want to create the new file (and validate that it can be done) or are you simply interested in manipulating the name of the file as a string? You need to be **WAY** more specific about what you want. This question is currently unanswerable. – jahroy Jun 12 '13 at 20:59
  • I must disagree as to whether this question is answered by the quoted post. The quoted post does not use Java 7. – fge Jun 12 '13 at 22:20

1 Answers1

1

This is 2013. This is Java 7. This is the time for Files and Path.

Base directory:

final Path baseDir = Paths.get("/path/to/baseDir");

Determine subdirectory for a file:

final String s = name.substring(name.length() - 2, name.length());

Create that directory:

final Path subDir = baseDir.resolve(s);
// Will not do anything if directory already exists...
// But will throw exception if unable to create
Files.createDirectories(subDir);

Write to the file:

final Path dst = subDir.resolve(name + ".doc");
Files.copy(src, dst);

Remove original:

Files.delete(src);

Or in one operation:

Files.move(src, dst);
fge
  • 119,121
  • 33
  • 254
  • 329