jueves, octubre 27, 2011

java leer archivo




Este es el codigo de un sencillo lector de archivos en java.





--> Lector.java

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 *
 * @author ing. Oscar Hurtado Morato
 */
public class Lector {

    //Charset "UTF-8","ISO-8859-1","latin1"
    private String line = "";
    //protected String fullPath;
    private BufferedReader br;
    //protected String chSet;
    private InputStreamReader str;

    public void instanciaArchivoAleerse(String fullPath, String charSet) throws FileNotFoundException {
        str = new InputStreamReader(new FileInputStream(fullPath), Charset.forName(charSet));
        br = new BufferedReader(str);
    }

    public String getLine() {
        return line;
    }

    public boolean readNextLine() {
        boolean ret = true;
        try {
            line = br.readLine();
            if (line == null) {
                ret = false;
            }
        } catch (IOException ex) {
            ret = false;
        }
        return ret;
    }
}




--------------------------------------------------------

LectorTest.java



import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ing. Oscar Hurtado Morato
 */
public class LectorTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        LectorTest lector = new LectorTest();
        lector.test();
    }

    private void test() {
        try {
            Lector lec = new Lector();
            String fullPath = "";
            String charset = "";
            fullPath = "d:/example.txt";
            charset = "latin1";
            lec.instanciaArchivoAleerse(fullPath, charset);
            String linea = "";
            while (lec.readNextLine()) {
                linea = lec.getLine();
                System.out.println(linea);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(LectorTest.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}





No hay comentarios.:

Publicar un comentario

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...