Różne sposoby czytania pliku tekstowego w Javie
W Javie istnieje wiele sposobów odczytywania pliku tekstowego, w zależności od rozmiaru danych i przypadku użycia. The Java.io I pakiety java.nio.file udostępniają kilka klas do efektywnej obsługi odczytu plików. Omówmy po kolei popularne podejścia.
1. Korzystanie z klasy BufferedReader
Buforowany czytnik klasa odczytuje tekst ze strumienia znaków i buforuje znaki w celu wydajnego odczytu. Często jest owinięty wokół Czytnik plików Lub Czytnik strumienia wejściowego aby poprawić wydajność.
Składnia
JavaBufferedReader in = nowy BufferedReader(Czytnik w rozmiarze int);
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 ); } }
Wyjście
Wyjście 2. Klasa FileReader do odczytu pliku tekstowego
The Klasa FileReader służy do odczytu plików tekstowych w Javie. Odczytuje znaki z pliku i nadaje się do czytania zwykłego tekstu. Konstruktory tej klasy zakładają, że domyślne kodowanie znaków i domyślny rozmiar buforu bajtów są odpowiednie.
Konstruktory zdefiniowane w tej klasie są następujące:
- FileReader (plik pliku): Tworzy nowy FileReader, biorąc pod uwagę plik, z którego ma zostać odczytany
- FileReader(FileDescriptor fd): Tworzy nowy FileReader, biorąc pod uwagę FileDescriptor do odczytu
- FileReader (ciąg nazwy pliku): Tworzy nowy FileReader, podając nazwę pliku, z którego ma zostać odczytany
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 ); } }
Wyjście
Wyjście 3. Klasa skanera do odczytu pliku tekstowego
Klasa skanera zapewnia prosty sposób czytania plików tekstowych i analizowania typów pierwotnych lub ciągów znaków za pomocą wyrażenia regularne . Dzieli dane wejściowe na tokeny za pomocą ogranicznika (domyślnie białych znaków).
Przykład 1: Z użyciem pętli
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 ()); } }
Wyjście
Wyjście Przykład 2: Bez użycia pętli
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 ()); } }
Wyjście
Wyjście 4. Odczyt całego pliku na liście
Możemy wczytać cały plik tekstowy do listy za pomocą Pliki.readAllLines() metoda z pakiet java.nio.file . Każda linia w pliku staje się jednym elementem na liście.
Składnia
public static List readAllLines (Ścieżka pathCharset cs) zgłasza wyjątek IOException
Ta metoda rozpoznaje następujące elementy jako terminatory linii:
- u000Du000A -> Powrót karetki + przesunięcie wiersza
- u000A -> Zasilanie liniowe
- u000D -> Powrót karetki
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 ()); } }
Wyjście
Wyjście 5. Przeczytaj plik tekstowy jako String
W Javie możemy odczytać cały plik tekstowy jako pojedynczy ciąg znaków. Jest to przydatne, gdy chcesz przetwarzać zawartość pliku jako całość, a nie wiersz po wierszu.
Składnia:
Dane ciągu = nowy String(Files.readAllBytes(Paths.get(fileName)));
Przykład:
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 ); } }
Wyjście
Wyjście