Diferents maneres de llegir un fitxer de text en Java

Diferents maneres de llegir un fitxer de text en Java

A Java hi ha diverses maneres de llegir un fitxer de text depenent de la mida de les dades i del cas d'ús. El java.io i paquets java.nio.file proporcionar diverses classes per gestionar la lectura de fitxers de manera eficient. Parlem un per un dels enfocaments comuns.

1. Utilitzant la classe BufferedReader

BufferedReader la classe llegeix el text d'un flux de caràcters i guarda els caràcters per a una lectura eficient. Sovint s'embolica al voltant d'a FileReader o InputStreamReader per millorar el rendiment.

Sintaxi

BufferedReader in = new BufferedReader (Lector amb mida 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  );      }   }   


Sortida

Utilitzant BufferReaderSortida

2. Classe FileReader per llegir un fitxer de text

El Classe FileReader s'utilitza per llegir fitxers de text en Java. Llegeix caràcters d'un fitxer i és adequat per llegir text sense format. Els constructors d'aquesta classe assumeixen que la codificació de caràcters per defecte i la mida de la memòria intermèdia de bytes per defecte són adequades. 

Els constructors definits en aquesta classe són els següents:

  • FileReader (fitxer de fitxer): Crea un nou FileReader donat el fitxer per llegir-lo
  • FileReader(FileDescriptor fd): Crea un nou FileReader donat el FileDescriptor per llegir
  • FileReader(String fileName): Crea un nou FileReader amb el nom del fitxer des del qual cal llegir
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  );      }   }   


Sortida

Utilitzant FileReaderSortida

3. Classe d'escàner per llegir fitxers de text

Classe d'escàner proporciona una manera senzilla de llegir fitxers de text i analitzar tipus o cadenes primitius utilitzant expressions regulars . Divideix l'entrada en fitxes utilitzant un delimitador (espai en blanc per defecte).

Exemple 1: Amb l'ús de bucles

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  ());      }   }   


Sortida

Utilitzant BufferReaderSortida

Exemple 2: Sense utilitzar bucles

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  ());      }   }   


Sortida

Lectura de lSortida

4. Llegint tot el fitxer en una llista

Podem llegir un fitxer de text sencer en una llista utilitzant el Files.readAllLines() mètode des del paquet java.nio.file . Cada línia del fitxer es converteix en un element de la llista.

Sintaxi

Public static List readAllLines(Path pathCharset cs) genera IOException

Aquest mètode reconeix el següent com a terminadors de línia: 

  • u000Du000A -> Retorn de carro + Avance de línia
  • u000A -> Avance de línia
  • u000D -> Retorn 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  ());      }   }   


Sortida

ReadFileIntoListSortida

5. Llegiu un fitxer de text com a cadena

Podem llegir un fitxer de text sencer com una sola cadena a Java. Això és útil quan voleu processar el contingut del fitxer com un tot en lloc de línia per línia.

Sintaxi:

Dades de cadena = new String(Files.readAllBytes(Paths.get(fileName)));

Exemple:

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  );      }   }   

Sortida

ReadTextAsStringSortida

Crea un qüestionari