דרכים שונות לקריאת קובץ טקסט ב-Java

דרכים שונות לקריאת קובץ טקסט ב-Java

ב-Java ישנן מספר דרכים לקרוא קובץ טקסט בהתאם לגודל הנתונים ולמקרה השימוש שלך. ה java.io ו חבילות java.nio.file לספק מספר שיעורים לטיפול בקריאת קבצים ביעילות. בואו נדון בגישות הנפוצות אחת לאחת.

1. שימוש במחלקת BufferedReader

BufferedReader class קוראת טקסט מזרם תווים ומאגרת את התווים לקריאה יעילה. לעתים קרובות הוא כרוך סביב א FileReader אוֹ InputStreamReader לשיפור הביצועים.

תַחבִּיר

BufferedReader in = new BufferedReader(Reader בגודל 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  );      }   }   


תְפוּקָה

שימוש ב-BufferReaderתְפוּקָה

2. מחלקה FileReader לקריאת קובץ טקסט

ה מחלקה FileReader משמש לקריאת קבצי טקסט ב-Java. הוא קורא תווים מקובץ ומתאים לקריאת טקסט רגיל. הבנאים של מחלקה זו מניחים שקידוד התווים המוגדר כברירת מחדל וגודל מאגר הבתים המוגדר כברירת מחדל מתאימים. 

הבנאים המוגדרים במחלקה זו הם כדלקמן:

  • FileReader (קובץ קובץ): יוצר FileReader חדש בהינתן הקובץ לקריאה ממנו
  • FileReader (FileDescriptor fd): יוצר FileReader חדש שניתן לקרוא ממנו את FileDescriptor
  • FileReader(String fileName): יוצר FileReader חדש עם שם הקובץ שממנו יש לקרוא
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  );      }   }   


תְפוּקָה

שימוש ב-FileReaderתְפוּקָה

3. כיתת סורק לקריאת קובץ טקסט

כיתת סורקים מספק דרך פשוטה לקרוא קבצי טקסט ולנתח סוגים או מחרוזות פרימיטיביות באמצעות ביטויים רגולריים . זה מפצל את הקלט לאסימונים באמצעות מפריד (כברירת מחדל לרווח לבן).

דוגמה 1: עם שימוש בלולאות

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


תְפוּקָה

שימוש ב-BufferReaderתְפוּקָה

דוגמה 2: בלי להשתמש בלולאות

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


תְפוּקָה

קורא את כל הקובץ ללא לולאהתְפוּקָה

4. קריאת הקובץ כולו ברשימה

אנו יכולים לקרוא קובץ טקסט שלם לתוך רשימה באמצעות ה Files.readAllLines() שיטה מה חבילת java.nio.file . כל שורה בקובץ הופכת לרכיב אחד ברשימה.

תַחבִּיר

רשימה סטטית ציבורית readAllLines(Path pathCharset cs) זורקת IOException

שיטה זו מזהה את הדברים הבאים כמסימי קו: 

  • u000Du000A -> החזרת כרכרה + הזנת קו
  • u000A -> הזנת קו
  • u000D -> החזרת כרכרה
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  ());      }   }   


תְפוּקָה

ReadFileIntoListתְפוּקָה

5. קרא קובץ טקסט כמחרוזת

אנו יכולים לקרוא קובץ טקסט שלם כמחרוזת אחת ב-Java. זה שימושי כאשר ברצונך לעבד את תוכן הקובץ כמכלול ולא שורה אחר שורה.

תַחבִּיר:

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

דוּגמָה:

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

תְפוּקָה

ReadTextAsStringתְפוּקָה

צור חידון