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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Forcing File to Have .txt Extension 1

Status
Not open for further replies.

BoulderBum

Programmer
Jul 11, 2002
2,179
US
I created some code to insure a file is saved as .txt (which also guards against saving something as something.txt.txt), but it feels kind of clumsy. I felt like I wanted to use File.getParent(), but I couldn't figure out a portable way to use it and preserve the file delimiter character ('/' or '\' or whatever depending on the system).

Here is what I did:

**********************************************
File fileName = fileChooser.getSelectedFile();
BufferedWriter output;

//get name part of file name and its extension,
//and seperate them for processing
//the first token is assumed to be the file name,
//and the second token is assumed to be the extension
//(which is disregarded in order to force .txt extension)[/green]
StringTokenizer fileNameAndExtension = new StringTokenizer( fileName.getName(), "." );

//get the directory of the file including file delimeter (e.g. file path + '\')[/green]
int directoryEnd = fileName.toString().lastIndexOf( fileName.getName() );
String directory = fileName.toString().substring( 0, directoryEnd );


//open output according to given directory, and force the file to have
//a .txt extension (after removing current extension if it exists)[/green]
output = new BufferedWriter( new FileWriter( directory +
fileNameAndExtension.nextToken() + ".txt" ) );

**********************************************

Is there a better way?
 
The system-dependent seperators can be retrieved : for both the pathseperator and the (file)seperator there are 2 methods for your convinience (one returning a String, the other returning a char)
Code:
    System.out.println("PathSeperator = " + File.pathSeparator);
    System.out.println("PathSeperatorChar = " + File.pathSeparatorChar);
Code:
    System.out.println("Seperator = " + File.separator);
    System.out.println("SeperatorChar = " + File.separatorChar);
 
I knew it had to be something simple like that! I was looking at the methods and neglecting the fields. Doh!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top