2009年4月3日

Java Read/Write File

Read File
private String readFile(String fileName, String fileCharacter)
{
String line = "";
try
{
FileInputStream fis = new FileInputStream(new File(fileName));
// java.io.FileNotFoundException
BufferedReader br =new BufferedReader(new InputStreamReader(fis,fileCharacter));
// java.io.UnsupportedEncodingException
   
// java.io.IOException
while(br.ready())
line += br.readLine();

    br.close();
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}

return line;
}
Write File
private void writeFile(String fileName, byte[] writeText)
{
try
{
// Create file
File file = new File(fileName);
FileOutputStream fout = new FileOutputStream(file);
fout.write(writeText);
fout.close();

}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}

沒有留言:

張貼留言