Difference between revisions of "JAVA: Read Text File"

From OnnoWiki
Jump to navigation Jump to search
Line 1: Line 1:
 
There are multiple ways of writing and reading a text file. this is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
 
There are multiple ways of writing and reading a text file. this is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
 +
 +
Ada beberapa cara untuk menulis dan membaca file teks. ini diperlukan saat menangani banyak aplikasi. Ada beberapa cara untuk membaca file teks biasa di Java mis. Anda dapat menggunakan FileReader, BufferedReader, atau Scanner untuk membaca file teks. Setiap utilitas menyediakan sesuatu yang istimewa mis. BufferedReader menyediakan buffering data untuk pembacaan cepat, dan Scanner menyediakan kemampuan parsing.
 +
  
 
Method:
 
Method:
Line 10: Line 13:
  
 
We can also use both BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.  
 
We can also use both BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.  
 +
 +
Kita juga dapat menggunakan BufferReader dan Scanner untuk membaca file teks baris demi baris di Java. Kemudian Java SE 8 memperkenalkan kelas Stream lain java.util.stream.Stream yang menyediakan cara malas dan lebih efisien untuk membaca file.
 +
  
 
Tip Note: Practices of writing good code like flushing/closing streams, Exception-Handling etc, have been avoided for better understanding of codes by beginners as well.
 
Tip Note: Practices of writing good code like flushing/closing streams, Exception-Handling etc, have been avoided for better understanding of codes by beginners as well.
 +
 +
Catatan Tip: Praktik menulis kode yang baik seperti aliran pembilasan/penutupan, Penanganan Pengecualian, dll, telah dihindari untuk pemahaman kode yang lebih baik oleh pemula juga.
 +
  
 
Let us discuss each of the above methods to a deeper depth and most importantly by implementing them via a clean java program.  
 
Let us discuss each of the above methods to a deeper depth and most importantly by implementing them via a clean java program.  
  
==Method 1: Using BufferedReader class==
+
Mari kita bahas masing-masing metode di atas secara lebih mendalam dan yang paling penting dengan mengimplementasikannya melalui program java yang bersih.
 +
 
 +
 
 +
==Method 1: Menggunakan Class BufferedReader==
  
 
This method reads text from a character-input stream. It does buffer for efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders as shown below as follows:
 
This method reads text from a character-input stream. It does buffer for efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders as shown below as follows:
 +
 +
Metode ini membaca teks dari aliran input karakter. Itu buffer untuk membaca karakter, array, dan garis secara efisien. Ukuran buffer dapat ditentukan, atau ukuran default dapat digunakan. Standarnya cukup besar untuk sebagian besar tujuan. Secara umum, setiap permintaan baca yang dibuat dari Pembaca menyebabkan permintaan baca yang sesuai dibuat dari karakter atau aliran byte yang mendasarinya. Oleh karena itu disarankan untuk membungkus BufferedReader di sekitar Pembaca yang operasi read() mungkin mahal, seperti FileReaders dan InputStreamReaders seperti yang ditunjukkan di bawah ini sebagai berikut:
 +
 +
  
 
  BufferedReader in = new BufferedReader(Reader in, int size);
 
  BufferedReader in = new BufferedReader(Reader in, int size);
Line 66: Line 82:
  
 
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.  
 
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.  
 +
 +
Kelas kenyamanan untuk membaca file karakter. Konstruktor kelas ini menganggap bahwa pengkodean karakter default dan ukuran buffer byte default sudah sesuai.
 +
  
 
Constructors defined in this class are as follows:
 
Constructors defined in this class are as follows:
 +
 +
Konstruktor yang didefinisikan dalam kelas ini adalah sebagai berikut:
 +
  
 
  FileReader(File file): Creates a new FileReader, given the File to read from
 
  FileReader(File file): Creates a new FileReader, given the File to read from
Line 73: Line 95:
 
  FileReader(String fileName): Creates a new FileReader, given the name of the file to read from
 
  FileReader(String fileName): Creates a new FileReader, given the name of the file to read from
  
Example:
+
Contoh:
  
 
  // Java Program to Illustrate reading from
 
  // Java Program to Illustrate reading from
Line 107: Line 129:
 
  If you want to code refer to GeeksforGeeks
 
  If you want to code refer to GeeksforGeeks
  
==Method 3: Using Scanner class==
+
==Method 3: Menggunakan Class Scanner==
  
 
A simple text scanner that can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
 
A simple text scanner that can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
  
===Example 1: With using loops===
+
Pemindai teks sederhana yang dapat mengurai tipe dan string primitif menggunakan ekspresi reguler. Pemindai memecah inputnya menjadi token menggunakan pola pembatas, yang secara default cocok dengan spasi putih. Token yang dihasilkan kemudian dapat diubah menjadi nilai dari jenis yang berbeda menggunakan berbagai metode berikutnya.
 +
 
 +
 
 +
 
 +
===Example 1: Dengan menggunakan loop===
  
 
  // Java Program to illustrate
 
  // Java Program to illustrate
Line 135: Line 161:
 
  If you want to code refer to GeeksforGeeks
 
  If you want to code refer to GeeksforGeeks
  
===Example 2: Without using loops===
+
===Example 2: Tanpa menggunakan loop===
  
 
  // Java Program to illustrate reading from FileReader
 
  // Java Program to illustrate reading from FileReader
Line 163: Line 189:
 
  If you want to code refer to GeeksforGeeks
 
  If you want to code refer to GeeksforGeeks
  
==Method 4: Reading the whole file in a List==
+
==Method 4: Membaca keseluruhan file di List==
  
 
Read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.  
 
Read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.  
 +
 +
Baca semua baris dari file. Metode ini memastikan bahwa file ditutup ketika semua byte telah dibaca atau kesalahan I/O, atau pengecualian runtime lainnya, dilemparkan. Byte dari file didekodekan menjadi karakter menggunakan charset yang ditentukan.
 +
  
 
Sintaks:
 
Sintaks:
Line 172: Line 201:
  
 
This method recognizes the following as line terminators:  
 
This method recognizes the following as line terminators:  
 +
 +
Method ini mengenali yang berikut sebagai terminator garis:
  
 
  \u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED
 
  \u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED
Line 219: Line 250:
 
  If you want to code refer to GeeksforGeeks
 
  If you want to code refer to GeeksforGeeks
  
==Method 5: Read a text file as String==
+
==Method 5: Membaca sebuah text file sebagai String==
  
 
Contoh
 
Contoh

Revision as of 07:11, 9 May 2022

There are multiple ways of writing and reading a text file. this is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.

Ada beberapa cara untuk menulis dan membaca file teks. ini diperlukan saat menangani banyak aplikasi. Ada beberapa cara untuk membaca file teks biasa di Java mis. Anda dapat menggunakan FileReader, BufferedReader, atau Scanner untuk membaca file teks. Setiap utilitas menyediakan sesuatu yang istimewa mis. BufferedReader menyediakan buffering data untuk pembacaan cepat, dan Scanner menyediakan kemampuan parsing.


Method:

  • Menggunakan Class BufferedReader
  • Menggunakan Class Scanner
  • Menggunakan Class File Reader
  • Membaca seluruh file dalam sebuah List
  • Membaca file text sebagai String

We can also use both BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.

Kita juga dapat menggunakan BufferReader dan Scanner untuk membaca file teks baris demi baris di Java. Kemudian Java SE 8 memperkenalkan kelas Stream lain java.util.stream.Stream yang menyediakan cara malas dan lebih efisien untuk membaca file.


Tip Note: Practices of writing good code like flushing/closing streams, Exception-Handling etc, have been avoided for better understanding of codes by beginners as well.

Catatan Tip: Praktik menulis kode yang baik seperti aliran pembilasan/penutupan, Penanganan Pengecualian, dll, telah dihindari untuk pemahaman kode yang lebih baik oleh pemula juga.


Let us discuss each of the above methods to a deeper depth and most importantly by implementing them via a clean java program.

Mari kita bahas masing-masing metode di atas secara lebih mendalam dan yang paling penting dengan mengimplementasikannya melalui program java yang bersih.


Method 1: Menggunakan Class BufferedReader

This method reads text from a character-input stream. It does buffer for efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders as shown below as follows:

Metode ini membaca teks dari aliran input karakter. Itu buffer untuk membaca karakter, array, dan garis secara efisien. Ukuran buffer dapat ditentukan, atau ukuran default dapat digunakan. Standarnya cukup besar untuk sebagian besar tujuan. Secara umum, setiap permintaan baca yang dibuat dari Pembaca menyebabkan permintaan baca yang sesuai dibuat dari karakter atau aliran byte yang mendasarinya. Oleh karena itu disarankan untuk membungkus BufferedReader di sekitar Pembaca yang operasi read() mungkin mahal, seperti FileReaders dan InputStreamReaders seperti yang ditunjukkan di bawah ini sebagai berikut:


BufferedReader in = new BufferedReader(Reader in, int size);

Contoh:

// Java Program to illustrate Reading from FileReader
// using BufferedReader Class
 
// Importing input output classes
import java.io.*;
 
// Main class
public class GFG {
 
    // main driver method
    public static void main(String[] args) throws Exception
    {
 
        // File path is passed as parameter
        File file = new File(
            "C:\\Users\\pankaj\\Desktop\\test.txt");
 
        // Note:  Double backquote is to avoid compiler
        // interpret words
        // like \test as \t (ie. as a escape sequence)
 
        // Creating an object of BufferedReader class
        BufferedReader br
            = new BufferedReader(new FileReader(file));
 
        // Declaring a string variable
        String st;
        // Condition holds true till
        // there is character in a string
        while ((st = br.readLine()) != null)
 
            // Print the string
            System.out.println(st);
    }
}

Output:

If you want to code refer to GeeksforGeeks

Method 2: Using FileReader class

Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.

Kelas kenyamanan untuk membaca file karakter. Konstruktor kelas ini menganggap bahwa pengkodean karakter default dan ukuran buffer byte default sudah sesuai.


Constructors defined in this class are as follows:

Konstruktor yang didefinisikan dalam kelas ini adalah sebagai berikut:


FileReader(File file): Creates a new FileReader, given the File to read from
FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from
FileReader(String fileName): Creates a new FileReader, given the name of the file to read from

Contoh:

// Java Program to Illustrate reading from
// FileReader using FileReader class
 
// Importing input output classes
import java.io.*;
 
// Main class
// ReadingFromFile
public class GFG {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Passing the path to the file as a parameter
        FileReader fr = new FileReader(
            "C:\\Users\\pankaj\\Desktop\\test.txt");
 
        // Declaring loop variable
        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);
    }
}

Output:

If you want to code refer to GeeksforGeeks

Method 3: Menggunakan Class Scanner

A simple text scanner that can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

Pemindai teks sederhana yang dapat mengurai tipe dan string primitif menggunakan ekspresi reguler. Pemindai memecah inputnya menjadi token menggunakan pola pembatas, yang secara default cocok dengan spasi putih. Token yang dihasilkan kemudian dapat diubah menjadi nilai dari jenis yang berbeda menggunakan berbagai metode berikutnya.


Example 1: Dengan menggunakan loop

// Java Program to illustrate
// reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
  public static void main(String[] args) throws Exception
  {
    // pass the path to the file as a parameter
    File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
    Scanner sc = new Scanner(file);
 
    while (sc.hasNextLine())
      System.out.println(sc.nextLine());
  }
}

Output:

If you want to code refer to GeeksforGeeks

Example 2: Tanpa menggunakan loop

// Java Program to illustrate reading from FileReader
// using Scanner Class reading entire File
// without using loop
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
 
public class ReadingEntireFileWithoutLoop
{
  public static void main(String[] args)
                        throws FileNotFoundException
  {
    File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
    Scanner sc = new Scanner(file);
 
    // we just need to use \\Z as delimiter
    sc.useDelimiter("\\Z");
 
    System.out.println(sc.next());
  }
}

Output:

If you want to code refer to GeeksforGeeks

Method 4: Membaca keseluruhan file di List

Read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.

Baca semua baris dari file. Metode ini memastikan bahwa file ditutup ketika semua byte telah dibaca atau kesalahan I/O, atau pengecualian runtime lainnya, dilemparkan. Byte dari file didekodekan menjadi karakter menggunakan charset yang ditentukan.


Sintaks:

public static List readAllLines(Path path,Charset cs)throws IOException

This method recognizes the following as line terminators:

Method ini mengenali yang berikut sebagai terminator garis:

\u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED
\u000A, LINE FEED
\u000D, CARRIAGE RETURN

Contoh

// Java program to illustrate reading data from file
// using nio.File
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;
public class ReadFileIntoList
{
  public static List<String> readFileInList(String fileName)
  {
 
    List<String> lines = Collections.emptyList();
    try
    {
      lines =
       Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
    }
 
    catch (IOException e)
    {
 
      // do something
      e.printStackTrace();
    }
    return lines;
  }
  public static void main(String[] args)
  {
    List l = readFileInList("C:\\Users\\pankaj\\Desktop\\test.java");
 
    Iterator<String> itr = l.iterator();
    while (itr.hasNext())
      System.out.println(itr.next());
  }
}

Output:

If you want to code refer to GeeksforGeeks

Method 5: Membaca sebuah text file sebagai String

Contoh

// Java Program to illustrate
// reading from text file
// as string in 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
  {
    String data = readFileAsString("C:\\Users\\pankaj\\Desktop\\test.java");
    System.out.println(data);
  }
}

Output:

If you want to code refer to GeeksforGeeks


Referensi