|
|
Title |
Text file Read/Write
|
Summary |
A simple pair of functions to read and write Strings to a file. |
Contributor |
John McTainsh
|
Published |
4-Nov-2000 |
Last updated |
4-Nov-2000 |
|
|
Description.
File IO forms some part of most applications today. It is simple to
perform and easy way to make persistent data. This note persistent
how to read text from and write text to a file.
The functions and how to use them.
Lets first introduce the functions.
/**
* Load the file into a StringBuffer for processing
* @param sFileName The fully qualified name of the file
* @param sData The text read from the file or
* the exception description if an error occured.
* @return True if the read was sucessful
*/
public static boolean loadFile( String sFileName, StringBuffer sData )
{
try
{
FileReader fr = new FileReader( sFileName );
char [] aryData = new char[1000];
//Keep reading until no more data remains
while( true )
{
int nRead = fr.read( aryData );
if( nRead < 0 )
{
break;
}
sData.append( aryData, 0, nRead );
}
fr.close();
return true;
}
//Catch any IO exceptions and put them in the return string
catch( IOException ioe )
{
sData.append( ioe );
return false;
}
}
/**
* Write the given data to sFileNamme
* @param sFileName The fully qualified name of the file
* @param sData The text to write to the file.
* @return True if the write was sucessful
*/
public static boolean saveFile( String sFileName, String sData )
{
try
{
FileWriter fw = new FileWriter( sFileName );
fw.write( sData, 0, sData.length() );
fw.flush();
fw.close();
return true;
}
//Catch any IO exceptions and put them in the return string
catch( IOException ioe )
{
return false;
}
}
Now lets use them. Read text from one file and write it
to another.
StringBuffer sFileData = new StringBuffer();
if( loadFile( "C:\\Temp\\Master.txt , sFileData );
saveFile( "C:\\Temp\\Master.bak , sFileData.toString() );
else
System.out.println( "Error: " + sFileData.toString() );
|