Diferentes maneiras de ler um arquivo de texto em Java

Diferentes maneiras de ler um arquivo de texto em Java

Em Java, existem várias maneiras de ler um arquivo de texto, dependendo do tamanho dos dados e do caso de uso. O java.io e Pacotes java.nio.file fornece várias classes para lidar com a leitura de arquivos com eficiência. Vamos discutir as abordagens comuns, uma por uma.

1. Usando a classe BufferedReader

Leitor Buffered classe lê texto de um fluxo de caracteres e armazena os caracteres em buffer para uma leitura eficiente. Muitas vezes é enrolado em torno de um Leitor de arquivos ou Leitor de entradaStream para melhorar o desempenho.

Sintaxe

BufferedReader in = new BufferedReader(Leitor em tamanho int);

Java
   import     java.io.*  ;   public     class   UsingBufferReader     {      public     static     void     main  (  String  []     args  )     throws     Exception  {          // Creating BufferedReader for Input      BufferedReader     bfri     =     new     BufferedReader  (      new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );      // Reading File name      String     path     =     bfri  .  readLine  ();      BufferedReader     bfro      =     new     BufferedReader  (  new     FileReader  (  path  ));      String     st  ;      while     ((  st     =     bfro  .  readLine  ())     !=     null  )      System  .  out  .  println  (  st  );      }   }   


Saída

UsandoBufferReaderSaída

2. Classe FileReader para leitura de arquivo de texto

O Classe FileReader é usado para ler arquivos de texto em Java. Ele lê caracteres de um arquivo e é adequado para leitura de texto simples. Os construtores desta classe assumem que a codificação de caracteres padrão e o tamanho do buffer de bytes padrão são apropriados. 

Os construtores definidos nesta classe são os seguintes:

  • Leitor de arquivos (arquivo de arquivo): Cria um novo FileReader dado o arquivo para leitura
  • FileReader (FileDescriptor fd): Cria um novo FileReader dado o FileDescriptor para leitura
  • FileReader (String nome do arquivo): Cria um novo FileReader com o nome do arquivo para leitura
Java
   import     java.io.*  ;   public     class   UsingFileReader     {      public     static     void     main  (  String  []     args  )     throws     Exception      {      BufferedReader     br     =     new     BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();      FileReader     fr     =     new     FileReader  (  path  );      int     i  ;          // Holds true till there is nothing to read      while     ((  i     =     fr  .  read  ())     !=     -  1  )      // Print all the content of a file      System  .  out  .  print  ((  char  )  i  );      }   }   


Saída

UsandoFileReaderSaída

3. Classe de scanner para leitura de arquivo de texto

Classe de scanner fornece uma maneira simples de ler arquivos de texto e analisar tipos primitivos ou strings usando expressões regulares . Ele divide a entrada em tokens usando um delimitador (por padrão, espaço em branco).

Exemplo 1: Com o uso de loops

Java
   import     java.io.*  ;   import     java.util.Scanner  ;   public     class   UsingScannerClass      {      public     static     void     main  (  String  []     args  )     throws     Exception      {      BufferedReader     br     =     new     BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();          // pass the path to the file as a parameter      File     file     =     new     File  (  path  );          Scanner     sc     =     new     Scanner  (  file  );      while     (  sc  .  hasNextLine  ())      System  .  out  .  println  (  sc  .  nextLine  ());      }   }   


Saída

UsandoBufferReaderSaída

Exemplo 2: Sem usar loops

Java
   import     java.io.*  ;   import     java.util.Scanner  ;   public     class   ReadingEntireFileWithoutLoop     {      public     static     void     main  (  String  []     args  )      throws     IOException      {      BufferedReader     br     =     new     BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();          File     file     =     new     File  (  path  );          Scanner     sc     =     new     Scanner  (  file  );      // we just need to use \Z as delimiter      sc  .  useDelimiter  (  '\Z'  );      System  .  out  .  println  (  sc  .  next  ());      }   }   


Saída

LendoEntireFileWithoutLoopSaída

4. Lendo o arquivo inteiro em uma lista

Podemos ler um arquivo de texto inteiro em uma lista usando o Arquivos.readAllLines() método do pacote java.nio.file . Cada linha do arquivo se torna um elemento da lista.

Sintaxe

Lista estática pública readAllLines (Path pathCharset cs) lança IOException

Este método reconhece o seguinte como terminadores de linha: 

  • u000D000A -> Retorno de carro + Alimentação de linha
  • u000A -> Alimentação de linha
  • u000D -> Retorno de carro
Java
   import     java.io.*  ;   import     java.nio.charset.StandardCharsets  ;   import     java.nio.file.*  ;   import     java.util.*  ;   public     class   ReadFileIntoList      {      public     static     List   <  String  >     readFileInList  (  String     fileName  )      {      // Created List of String      List   <  String  >     lines     =     Collections  .  emptyList  ();          try     {      lines     =     Files  .  readAllLines  (      Paths  .  get  (  fileName  )      StandardCharsets  .  UTF_8  );      }     catch  (  IOException     e  )     {      e  .  printStackTrace  ();      }          return     lines  ;      }          public     static     void     main  (  String  []     args  )      throws     IOException      {          BufferedReader     br     =     new      BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();          List     l     =     readFileInList  (  path  );          // Iterator iterating over List      Iterator   <  String  >     itr     =     l  .  iterator  ();          while     (  itr  .  hasNext  ())      System  .  out  .  println  (  itr  .  next  ());      }   }   


Saída

ReadFileIntoListSaída

5. Ler um arquivo de texto como String

Podemos ler um arquivo de texto inteiro como uma única String em Java. Isso é útil quando você deseja processar o conteúdo do arquivo como um todo, em vez de linha por linha.

Sintaxe:

Dados de string = new String(Files.readAllBytes(Paths.get(fileName)));

Exemplo:

Java
   package     io  ;   import     java.nio.file.*  ;   public     class   ReadTextAsString     {      public     static     String     readFileAsString  (  String     fileName  )      throws     Exception      {      String     data     =     ''  ;      data     =     new     String  (      Files  .  readAllBytes  (  Paths  .  get  (  fileName  )));      return     data  ;      }      public     static     void     main  (  String  []     args  )     throws     Exception      {      BufferedReader     br     =     new     BufferedReader  (  new     InputStreamReader  (  System  .  in  ));      System  .  out  .  print  (  'Enter the Path : '  );          // Reading File name      String     path     =     br  .  readLine  ();          String     data     =     readFileAsString  (  path  );          System  .  out  .  println  (  data  );      }   }   

Saída

ReadTextAsStringSaída

Criar questionário