martes, enero 16, 2007

[Java] Lee archivo con getResource

Este ejemplo muestra como leer un archivo de texto utilizando "getResource()".

Para aquellos que ya utilizaron getResource y se chocaron con el problema que al mostrar el path les salia algo como esto:
/c:/program%20files/...
La idea que hay que tomar en cuenta es que las direcciones "URL" no contienen espacios, por lo tanto son reeplazadas por el caracter "%20", para ello se repara el path utilizando replaceAll("%20"," ").


Nota: El ejemplo aqui mostrado lee el archivo "getTextResource.java" y lo muestra.

Espero y les sea de utilidad.




____________________________________________________________________________

import java.io.*;
import java.net.*;

/*
*
*@author Oscar Hurtado Morato
*
*/
public class getTextResource {
public getTextResource() {
}
public static void main(String[] arg) {
try{
getTextResource ex=new getTextResource();
ex.leeArchivo();
}
catch(Exception e){
e.printStackTrace();
}
}
public void leeArchivo()throws IOException {
URL url=this.getClass().getResource("getTextResource.java");
String path=url.getPath();
path=path.replaceAll("%20"," ");
System.out.println(path);
//lee el file
BufferedReader br = new BufferedReader(new FileReader(path));
String thisLine="";
String retDoc="";
while ((thisLine = br.readLine()) != null) {
retDoc=retDoc+thisLine+"\n";
}
System.out.println(retDoc);
}
}

viernes, enero 12, 2007

[Java] File Download Servlet

Aqui les va el codigo para hacer "Dowload" de un fichero que se encuentre en el servidor, hacia el cliente.
Espero y les sirva.


----------------------------------------------------------------------------------------
1. Crear una pagina html con el nombre de "download.html", en el siguiente directorio
../webapps/nombre proyecto/jsp/ejemplos
Ojo: nombre proyecto se refiere al nombre que "Usted" le puso a su proyecto (que se encuentra en el directorio "webapps").Si por ejemplo este se llamase "prueba1", entonces el path seria como sigue:...webapps\prueba1\jsp\ejemplos
Que contenga el siguiente codigo:




<%@page contentType="text/html"%>
<html>
<head><title>jspQuery</title></head>
<body>
<form action="/nombre proyecto/servlet/ejemplos.Download">
<p><font color="#FFFFFF" size="1"
face="Verdana, Arial, Helvetica, sans-serif"><strong>
</strong></font></p>
<p>
<input type="submit" value="Download" name="dato"
>
</p>
<p> </p>
<p> </p>
</form>
</body>
</html>






2. Crear un fichero bajo el nombre de: "Download.java" en la siguiente direccion:
\webapps\nombre proyecto\WEB-INF\classes\ejemplos
Conteniendo el siguiente codigo:




/*
* Download.java
*
* Created on Jan 12, 2006, 04:00 PM
*/
package ejemplos;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* @author Oscar Hurtado Morato
* @version 1.0
*/
public class DownloadError extends HttpServlet {
/** Initializes the servlet.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
/** Destroys the servlet.
*/
public void destroy() {
}
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, java.io.IOException {
//Aqui se colocan el path y el nombre del file a hacerse upload
String filePath = "c:/";
String fileName = "prueba.txt";
FileInputStream fileToDownload = new FileInputStream(filePath);
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition","attachment; filename="+fileName);
response.setContentLength(fileToDownload.available());
int c;
while((c=fileToDownload.read()) != -1){
out.write(c);
}
out.flush();
out.close();
fileToDownload.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, java.io.IOException {
processRequest(request, response);
}
}




3. Fin.

java.net.SocketException: Software caused connection abort: socket write error

JAVA : Utilizando la librería " org.apache.commons.net.ftp ", encontré que al listar los archivos del servidor FTP se generaba...