Ler do Arquivo (.txt)

Estou precisando a partir de uma página .jsp, pega uma String de um arquivo TXT, como é que eu faço isso??

Alguem poderia tentar me explicar ou em passar um tutorial :?:

Obrigado Pessoal :!:
Espero Respostas…

bota isso no teu servlet ou cria uma taglib pra fazer isso ;b

import java.io.FileReader;
import java.util.Scanner;

public class ReadFile {
	
	public static void main( String[] a ) throws Exception {
		
		FileReader file = new FileReader( "C:\\arquivo.txt" );
		Scanner in = new Scanner( file );
		
		while( in.hasNext() )
			System.out.println( in.nextLine() );
	
	}
}

Detalhe: java.util.Scanner faz parte da JRE 1.5 (5.0)…
Se estiver usando uma versão anterior, isso deve funcionar:

    private void lerArquivo() {
        FileInputStream fin = null;
        DataInputStream stream = null;

        try {
            fin = new FileInputStream("c:\\logfile.txt");
            stream = new DataInputStream(fin);

            while (0 < stream.available()) {
                System.out.println(stream.readLine());
            }

        } catch (IOException e) {
            System.err.println("Unable to read from file");
            System.exit(-1);
        } finally {
            try {
                if (null != stream) stream.close();
                if (null != fin) fin.close();
            } catch (IOException e) {
            }
        }
    }

Cheers!

Galera preciso de ajuda urgente!!!

Procurei em toda web e não consegui nada que me ajudasse.

Preciso ler informações de modelagem de banco de dados antiga pelo java.
por exemplo em delphi eu tenho:

type

// Declaração da Estrutura
TPessoa = record
Nome: String[20];
Email: String[20];
end;

dai no delphi eu faço a associação deste arquivo de estrutura e na hora de fazer a leitura.
exemplo no delphi:

arq: file of Tpessoa
reg:Tpessoa

assingfile(arq,c:\dados.dat);
reset (arq)
read(arq,reg)
(…)

Como faço para realizar a leitura disso em Java?

Tenta com esta classe. Ela funciona perfeitamente pra mim e eu faço leitura de mais ou menos 300 arquivos dia.

Fiz também um exemplo básico da JSP prá pegar esse arquivo e processá-lo. Existem outras formas de se fazer, no entanto esse já é um bom caminho prá se melhorar.

Abraços e boa sorte.


// CLASSE JAVA
package pkgArquivo;

import java.io.*;
import java.io.BufferedReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.GenericServlet;
import org.apache.commons.fileupload.*;

/**
 *
 * @author Marco Aurélio Gomes da Silva
 *
 */
public class clsArquivo {

    /** Creates a new instance of clsArquivos */
    public clsArquivo() { }

    public String lerTXT(String __ARQUIVO) throws Exception
    {
        try
        {
            BufferedReader arquivo =  new BufferedReader(new FileReader(__ARQUIVO));
            String str = null;
            int j = 0;

            // Conta quantas linhas tem o arquivo
            // Arqui você pode fazer o que quiser com o arquivo, inclusive a leitura do mesmo
            while((str = arquivo.readLine()) != null) { j++; } str = null;

            arquivo.close();

            return String.valueOf(j);;
        }
        catch(Exception err)
        {
            throw err;
        }
    }
}

// PÁGINA INDEX.JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

<html>
 <head>
 
 <meta http-equiv="Content-Type" content="multipart/form-data; charset=ISO-8859-1">
 <title>UPLOAD</title>
 </head>
 <body style="font-family: Arial; font-size: 12px">
    <form method="post" action="leitura.jsp" enctype="multipart/form-data">
    <table width="100%" cellpadding="0" cellspacing="0" align="center" border="0">
      <tr>
        <td>Selecione o Arquivo</td>
      </tr>
      <tr>
        <td><input type="file" name="arquivo"></td>
      </tr>
      <tr>
        <td><input type="submit" value="Envia"></td>
      </tr>
    </table>
   </form>
 </body>
 </html>

// PÁGINA LEITURA.JSP
 <%@page language="java" %>
 <%@page contentType="text/html; charset=ISO-8859-1"%>
 <%@page pageEncoding="ISO-8859-1"%>
 <%@page import="org.apache.commons.fileupload.*"%>
 <%@page import="java.util.List"%>
 <%@page import="java.io.File"%>
 <%@page import="java.util.Iterator"%>
 <%@page import="java.lang.Object"%>
 <%@page import="javax.servlet.GenericServlet"%>
 <%@page import="pkgArquivo.clsArquivo"%>
  
 <html>
 <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Recepção de arquivo</title>
 </head>
 <body>
    <%
       try
       {
           DiskFileUpload upload = new DiskFileUpload();
           // Limite de 3Mb para o arquivo
           upload.setSizeMax(1024*1024*3);
           
           // Efetua parse do REQUEST para aquisição dos ítens do REQUEST
           List items = upload.parseRequest(request);
           Iterator itr = items.iterator();
           while(itr.hasNext())
           {
               FileItem item = (FileItem) itr.next();
               
               // Verificar se o ítem não é um campo de formulário ou um arquivo para UPLOAD
               if(!item.isFormField())
               {
                   File fullFile = new File(item.getName());
                   // Pega o nome do Arquivo
                   String nome = fullFile.getName();
                   // Pega a extensão do arquivo
                   String extensao = nome.substring(nome.length()-3,nome.length());
                   String arquivo_salvo = fullFile.getName();
                   File savedFile = new File(config.getServletContext().getRealPath("/anexos/"),arquivo_salvo);
                   item.write(savedFile);
                   
                   // Faz a leitura do Arquivo
                   String Arquivo = savedFile.getAbsolutePath();
                   clsArquivo objArquivo = new clsArquivo();
                   
                   Arquivo = objArquivo.lerTXT(Arquivo);
                   out.print(Arquivo);
               }
           }
       }
       catch(Exception err)
       {
           throw err;
       }
 %>
 </body>
 </html>