File Handling in Java
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.
There are several method to read a file there are some Classes to achieve that.
(a)FileInputStream
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;import java.nio.file.Paths;
import java.util.List;
extended method from java.io.Reader.Use to read bytes & convert that to Srring.
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.
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();
BufferedReader bufferedReader = new BufferedReader((new FileReader(file)));
String content = "";
String line = null;
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.
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
Post a Comment