Pages

Saturday, June 25, 2011

JAVA Code Snippet

String.Format(for (int i = 0; i < names.length; i++) {
                    //out.println("
" + names[i]);
                    out.print(String.format("%s %s", "
", names[i])
);
                }



Enumeration
 Enumeration params = request.getParameterNames();
        while (params.hasMoreElements())
        {
// Get the next parameter name.
            String paramName = params.nextElement();






Reading Resource File
public void testParsLocalfile() {
        String resourceLocation="/examples/documents/ABC_Catalyst.xml";
        URL result = getClass().getResource(resourceLocation);
        InputStream stream=null;
        try {
            stream = result.openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assertTrue("File is not exists", stream!=null);
   
        try {
            stream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


Uploading files

InputStream in = request.getInputStream();

// The file is always saved with the same name (just for this demo).
String path =this.getServletContext().getRealPath("/tmp/uploaded_file.txt");
OutputStream fileOut = new BufferedOutputStream(
new FileOutputStream(path));
// Create a buffer for reading bytes from the input stream.
byte[] buff = new byte[4096];
int len;

// Read bytes from the input stream, and write them to the file.
while ((len = in.read(buff)) > 0)
{
fileOut.write(buff, 0, len);
}
fileOut.close();

No comments:

Post a Comment