Dažādi teksta faila lasīšanas veidi Java

Dažādi teksta faila lasīšanas veidi Java

Programmā Java ir vairāki veidi, kā lasīt teksta failu atkarībā no datu lieluma un lietošanas gadījuma. The java.io un java.nio.file pakotnes nodrošināt vairākas klases, lai efektīvi apstrādātu failu lasīšanu. Apspriedīsim izplatītākās pieejas pa vienai.

1. BufferedReader klases izmantošana

BufferedReader klase nolasa tekstu no rakstzīmju straumes un buferē rakstzīmes efektīvai lasīšanai. To bieži aptin ap a FileReader vai InputStreamReader lai uzlabotu veiktspēju.

Sintakse

BufferedReader in = new BufferedReader(Reader int izmērā);

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


Izvade

Izmantojot BufferReaderIzvade

2. FileReader klase teksta faila lasīšanai

The FileReader klase tiek izmantots teksta failu lasīšanai Java valodā. Tas nolasa rakstzīmes no faila un ir piemērots vienkārša teksta lasīšanai. Šīs klases konstruktori pieņem, ka noklusējuma rakstzīmju kodējums un noklusējuma baitu bufera lielums ir piemēroti. 

Šajā klasē definētie konstruktori ir šādi:

  • FileReader (faila fails): Izveido jaunu FileReader, ņemot vērā failu, no kura lasīt
  • FileReader (FileDescriptor fd): Izveido jaunu FileReader, ņemot vērā FileDescriptor, no kura lasīt
  • FileReader (virknes faila nosaukums): Izveido jaunu FileReader, ņemot vērā lasāmā faila nosaukumu
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  );      }   }   


Izvade

Izmantojot programmu FileReaderIzvade

3. Skenera klase teksta faila lasīšanai

Skeneru klase nodrošina vienkāršu veidu, kā lasīt teksta failus un parsēt primitīvus tipus vai virknes, izmantojot regulāras izteiksmes . Tas sadala ievadi marķieros, izmantojot atdalītāju (pēc noklusējuma atstarpes).

1. piemērs: Izmantojot cilpas

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


Izvade

Izmantojot BufferReaderIzvade

2. piemērs: Neizmantojot cilpas

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


Izvade

Lasa visu failu bez cilpasIzvade

4. Visa faila lasīšana sarakstā

Mēs varam nolasīt visu teksta failu sarakstā, izmantojot Files.readAllLines() metode no java.nio.file pakotni . Katra faila rinda kļūst par vienu elementu sarakstā.

Sintakse

public static Saraksts readAllLines(Path pathCharset cs)throws IOException

Šī metode kā līnijas izbeigšanas punktus atpazīst: 

  • u000Du000A -> Karietes atgriešana + rindas padeve
  • u000A -> Līnijas padeve
  • u000D -> Karietes atgriešana
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  ());      }   }   


Izvade

ReadFileIntoListIzvade

5. Lasiet teksta failu kā virkni

Mēs varam lasīt visu teksta failu kā vienu virkni Java. Tas ir noderīgi, ja vēlaties apstrādāt faila saturu kopumā, nevis rindiņu pa rindiņai.

Sintakse:

Virknes dati = new String(Files.readAllBytes(Paths.get(fileName)));

Piemērs:

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

Izvade

ReadTextAsStringIzvade

Izveidojiet viktorīnu