Wednesday 27 August 2008

Read write file stored in class folder of webapp

Read data from classes folder in WEB-INF.


Insure that text/xml file is packaged into the classes folder


Create a utility class to do file reading. This was tested in weblogic and tomcat


See code below:


package com.mp.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileReader {


public String readTextFile(final String name) throws Exception {
StringBuffer xmlFromFile = new StringBuffer();
InputStream instr = null;
instr = getFilePath2(name);

if (instr == null)
throw new FileNotFoundException();
InputStreamReader streamreader= null;

try {

streamreader= new InputStreamReader(instr);
int x = 0;
x = streamreader.read();
char c;
while (x != -1) {
c= (char) x;
xmlFromFile.append(c);
x = streamreader.read();

}

} catch (Exception e) {

System.out.println("Exception " + e.getMessage());
throw e;

} finally {
streamreader.close();

}

return xmlFromFile.toString();

}




public byte[] readBinFileFromClassPath(final String name) throws Exception {

byte bytearray[]= null;
FileInputStream fileinputstream=null;
try {

fileinputstream = new FileInputStream(getFilePath(name));
int numberBytes = fileinputstream.available();
bytearray = new byte[numberBytes];
fileinputstream.read(bytearray);

} catch (Exception e) {
System.out.println("Exception " + e.getMessage());
throw e;

} finally {
if(fileinputstream!=null)
fileinputstream.close();
}

return bytearray;
}




public byte[] readBinFilePath(final String name) throws Exception {

byte bytearray[]= null;
FileInputStream fileinputstream=null;
try {

fileinputstream = new FileInputStream(name);
int numberBytes = fileinputstream.available();
bytearray = new byte[numberBytes];
fileinputstream.read(bytearray);

} catch (Exception e) {
System.out.println("Exception " + e.getMessage());
throw e;

} finally {
if(fileinputstream!=null)
fileinputstream.close();
}

return bytearray;
}




public void writeBinFileToPath(String name, byte data[]) throws IOException{


FileOutputStream fileoutputstream =new FileOutputStream(name);

try {
fileoutputstream.write(data );


} catch (IOException e) {
System.out.println(e.getMessage());

}finally{
if(fileoutputstream!=null)
fileoutputstream.close();
data=null;
}

}





private InputStream getFilePath2(String filename) {
return this.getClass().getClassLoader().getResourceAsStream(filename);

}


private String getFilePath(String filename) throws FileNotFoundException {
String path=this.getClass().getClassLoader().getResource(filename).getPath();
if ("".equals(path))
throw new FileNotFoundException();
return path;

}






}


No comments: