0 votes
1 view
in Java by (4.1k points)

It appears there are different methods to read and write data of files in Java.

I want to read ASCII data from a file. What are the potential ways and their differences?

1 Answer

0 votes
by (46.1k points)

   Here are some ways of reading files:

  • Using BufferedReader: This method indicates text from a character-input stream. It does a buffer for an effective reading of characters, arrays, and lines.

The buffer size may be defined, or the default size may be practiced. The default is big enough for most purposes.

In common, each read request made of a Reader causes a similar read request to be made of the underlying character or byte stream. It is therefore desirable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

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

Example:

// Java Program to illustrate reading from FileReader 

// using BufferedReader 

import java.io.*; 

public class ReadFromFile2 

  public static void main(String[] args)throws Exception 

  { 

  // We need to give file path as the parameter: 

  // double backquote is to avoid compiler interpret words 

  // like \test as \t (ie. as a escape sequence) 

  File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt"); 

    BufferedReader br = new BufferedReader(new FileReader(file)); 

  String st; 

  while ((st = br.readLine()) != null) 

    System.out.println(st); 

  } 

 

  • Using FileReader class: Convenience class for expressing character files. The constructor of this class finds that the default character encoding and the default byte-buffer size are relevant.

Constructors defined in this class are:

// Constructs a new FileReader, given the

// File to read from.

FileReader(File file)

// Constructs a new FileReader, given the

// FileDescriptor to read from.

FileReader(FileDescriptor fd)

// Creates a new FileReader, given the

// name of the file to read from.

FileReader(String fileName)

// Java Program to illustrate reading from 

// FileReader using FileReader 

import java.io.*; 

public class ReadingFromFile 

  public static void main(String[] args) throws Exception 

  { 

    FileReader fr = 

      new FileReader("C:\\Users\\pankaj\\Desktop\\test.txt"); 

    int i; 

    while ((i=fr.read()) != -1) 

      System.out.print((char) i); 

  } 

 

  • Using Scanner class: A simple text scanner which can parse primitive types and strings using normal expressions.

A Scanner splits its input into tokens using a delimiter pattern, which by default equals whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

// Java Program to demonstrate reading from Text File 

// applying Scanner Class 

import java.io.File; 

import java.util.Scanner; 

public class ReadFromFileUsingScanner 

  public static void main(String[] args) throws Exception 

  {  

    File file = 

      new File("C:\\Users\\pankaj\\Desktop\\test.txt"); 

    Scanner sc = new Scanner(file);  

    while (sc.hasNextLine()) 

      System.out.println(sc.nextLine()); 

  } 

Reading the full file in a List: Read all lines from a file. This method assures that the file is closed when all bytes have been read or an I/O error, or another runtime anomaly, is thrown. Bytes from the file are decoded into characters using the defined charset.

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

This method accepts the following as line terminators:

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

\u000A, LINE FEED

\u000D, CARRIAGE RETURN

// Java program to demonstrate reading data from a file 

// applying 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()); 

  } 

Related questions

0 votes
1 answer
asked Jul 9, 2019 in Java by Aditya98 (1.3k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...