user1131227
user1131227

Reputation: 59

Detect when file can't be created because of bad characters in name

Can anyone tell me how to cope with illegal file names in java? When I run the following on Windows:

File badname = new File("C:\\Temp\\a:b");

System.out.println(badname.getAbsolutePath()+" length="+badname.length());

FileWriter w = new FileWriter(badname);
w.write("hello world");
w.close();

System.out.println(badname.getAbsolutePath()+" length="+badname.length());

The output shows that the file has been created and has the expected length, but in C:\Temp all I can see is a file called "a" with 0 length. Where is java putting the file?

What I'm looking for is a reliable way to throw an error when the file can't be created. I can't use exists() or length() - what other options are there?

Upvotes: 1

Views: 352

Answers (5)

Harry Johnston
Harry Johnston

Reputation: 36318

In that particular example, the data is being written to a named stream. You can see the data you've written from the command line as follows:

 more < .\a:b

For information about valid file names, look here.

To answer your specific question: exists() should be sufficient. Even in this case, after all, the data is being written to the designated location - it just wasn't where you expected it to be! If you think this case will cause problems for your users, check for the presence of a colon in the file name.

Upvotes: 2

Azodious
Azodious

Reputation: 13872

Get the file name first:

String fileName = fullPath.substring(fullPath.lastIndexOf('\\'), fullPath.length);

Create an array of all special chars not allowed in file names.

for each char in array, check if fileName contains it. I guess, Java has a pre-built API for it.

Check this.

Note: This solution assumes that parent directory exists

Upvotes: 0

George
George

Reputation: 4109

You can use File.renameTo(File dest);.

Upvotes: 0

npinti
npinti

Reputation: 52185

You should take a look at Regular Expressions and create a pattern which will match any illegal character, something like this:

String fileName = "...";
Pattern pattern = Pattern.compile("[:;!?]");
Matcher matcher = pattern.match(fileName);

if (matcher.find())
{
    //Do something when the file name has an illegal character.
}

Note: I have not tested this code, but it should be enough to get you on the right track. The above code will match any string which contains a :, ;, `!' and '?'. Feel free to add/remove as you see fit.

Upvotes: 0

Bry6n
Bry6n

Reputation: 1979

I would suggest looking at Regular Expressions. They allow you to break apart a string and see if certain characteristics apply. The other method that would work is splitting the String into a char[], and then processing each point to see what's in it, and if it's legal... but I think RegEx would work much better.

Upvotes: 1

Related Questions