BoulderBum
Programmer
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?
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?