File Handling in Java


Java - Files and I/O - Tutorialspoint
Any file in the computer system stored as one dimensional byte array.So we want to read or write any file we want to read & write bits one by one.Bit this is very low level operation.So java introduced several Classes to achieve that easily.

1.Read File
There are several method to read a file there are some Classes to achieve that.

(a)FileInputStream
extended method from java.io.Reader.Use to read bytes & convert that to Srring.

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;import java.nio.file.Paths;
import java.util.List;

public class AppInizailzer {
    public static void main(String[] args) throws IOException {
    File file;//pointer
    file = new File("file path");
    FileInputStream fileInputStream = new FileInputStream(file);
    byte[] fileBytes = new byte[fileInputStream.available()];
    fileInputStream.read(fileBytes);
    fileInputStream.close();
    String s = new String(fileBytes);
    System.out.println(s);
    }
}

(b)FileReader
Child class of  FileInputStream. Must specify buffer size.This reader can use for read a text file.Read character by character.

FileReader fileReader = new FileReader(file);
char[] chars = new char[1024];//2kb buffer standard

// int read = fileReader.read(chars);
// System.out.println(read);//return char count
// int read1 = fileReader.read(chars);

//return -1,after reading
System.out.println(read1);
String content = "";

while (fileReader.read(chars) != -1) {
    content += new String(chars);
}

System.out.println(content);
fileReader.close();


(c)BufferedReader
Chining FileReader from BufferedReader. Increase its possibility.This reader read line by line.

BufferedReader bufferedReader = new BufferedReader((new FileReader(file)));
String content = "";
String line = null;

while ((line = bufferedReader.readLine()) != null) {
    content += line + "\n";
}
System.out.println(content);
bufferedReader.close();

(d)Java NIO(new input/output)
This method read whole file as one.
 Path path = Paths.get("Your path");
List<String> lines = Files.readAllLines(path);
 for (String line1 : lines) {
    System.out.println(line1);
}

                                                                                                                                    to be continued..



Comments

Popular posts from this blog

Hibernate-2

Hibernate-1

Avoid Round-off error in large & Small numbers using BigDecimal Class in Java